CakePHP 3 - Query builder properly not working for HasMany associations

走远了吗. 提交于 2019-12-22 01:31:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!