加入查询仅从一个 table cakephp 3 检索数据

Join query retrieving data from only one table cakephp 3

我是 cakephp 新手。我使用查询构建器使用加入 cakephp 查询 builder.But 从两个 table 中获取详细信息 我正在编写的查询仅从一个 table 中获取详细信息。也需要帮助从其他 table 获取数据。

这是我通过加入两个 table 来获取数据的代码:

public function edit($id = null) {

    $events_table = TableRegistry::get('Events');

    $events = $events_table->find('all') 
            ->hydrate(false)
            ->join([
            'CourseType'=>  [
                        'table'      => 'coursetype',
                        'type'       => 'LEFT',
                        'conditions' => 'Events.type = CourseType.coursetype_id',
                    ]                   
            ])->where(['Events.id' => $id]);

     $event = $events->toArray();       
     $this->set('event', $event);
}

因此,我只能从事件 table 中获取详细信息。但我需要来自 coursetype also.Any 帮助的数据,我们将不胜感激。谢谢。

您的解决方案在这里:CakePHP find method with JOIN

手动添加联接不会导致选择任何其他数据,您必须通过 select() 方法指定要选择的字段来自行完成此操作。

$events = $events_table
    ->find('all') 
    ->hydrate(false)
    ->select($events_table)
    // either add the fields one by one, or pass a table object
    // as above to select all fields of the table
    ->select(['CourseType.id', 'CourseType.xyz', /* ... */])
    // ...

我建议改用 use containments,即设置所需的关联(如果尚未存在),然后只需使用 contain():

$events = $events_table
    ->find('all') 
    ->hydrate(false)
    ->contain('CourseType')
    ->where(['Events.id' => $id]);

另见