CakePHP 3 - 查询生成器无法正常工作,无法用于 HasMany 关联



表 : 服务

+-----+--------------+
| id  |  title       |
+-----+--------------+
| 1   | Service 1    |
+-----+--------------+
| 2   | Service 2    |
+-----+--------------+

表 : 工作坊 { 有WorkshopServices }

+-----+---------------+
| id  |  title        |
+-----+---------------+
| 1   | Workshop 1    |
+-----+---------------+
| 2   | Workshop 2    |
+-----+---------------+

表 : 车间服务

+-----+--------------+-------------+
| id  |  workshop_id |  service_id |
+-----+--------------+-------------+
| 1   |  1           |  1          |
+-----+--------------+-------------+
| 2   |  1           |  2          |
+-----+--------------+-------------+

我想通过service_id找到Workshops

我的查询

$this->Workshops->find()
    ->contain([
        'WorkshopServices'
    ])
    ->where([
        'WorkshopServices.service_id IN'=>[1,2,3]
    ]);

查询结果

Unknown column `WorkshopServices.service_id` in 'where clause' 

实际上Workshops表不会与表生成任何WorkshopServices JOIN

如何编写查询以从Query Builder中获得正确的结果?

使用匹配:

$array = [1,2,3];
$this->Workshops->find()
    ->matching('WorkshopServices', function ($q) use($array) {
       return $q->where(['WorkshopServices.service_id IN' => $array])
    });

我更新了@GabrielFerreira的查询并按WorkshopServices.workshop_id对行进行分组,这个解决方案满足我的问题

$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']);

最新更新