问题
Table : Services
+-----+--------------+
| id | title |
+-----+--------------+
| 1 | Service 1 |
+-----+--------------+
| 2 | Service 2 |
+-----+--------------+
Table : Workshops { HasMany
WorkshopServices
}
+-----+---------------+
| id | title |
+-----+---------------+
| 1 | Workshop 1 |
+-----+---------------+
| 2 | Workshop 2 |
+-----+---------------+
Table : WorkshopServices
+-----+--------------+-------------+
| id | workshop_id | service_id |
+-----+--------------+-------------+
| 1 | 1 | 1 |
+-----+--------------+-------------+
| 2 | 1 | 2 |
+-----+--------------+-------------+
I want to find Workshops
by service_id
My Query
$this->Workshops->find()
->contain([
'WorkshopServices'
])
->where([
'WorkshopServices.service_id IN'=>[1,2,3]
]);
Query Result
Unknown column `WorkshopServices.service_id` in 'where clause'
Actually Workshops
table is not generating any JOIN
with WorkshopServices
table.
How can I write the query to get proper result from Query Builder
?
回答1:
Use matching:
$array = [1,2,3];
$this->Workshops->find()
->matching('WorkshopServices', function ($q) use($array) {
return $q->where(['WorkshopServices.service_id IN' => $array])
});
回答2:
I updated @GabrielFerreira's query and Grouping the rows by
WorkshopServices.workshop_id
, This solution meet my Problem
$array = [1,2,3];
$this->Workshops->find()
->select([
'title'=>'Workshops.title',
'id'=>'Workshops.id',
])
->matching('WorkshopServices', function ($q) use($array) {
return $q->where(['WorkshopServices.service_id IN' => $array]);
})
->group(['WorkshopServices.workshop_id']);
来源:https://stackoverflow.com/questions/46909779/cakephp-3-query-builder-properly-not-working-for-hasmany-associations