简体   繁体   English

联接查询仅从一个表中获取数据cakephp 3

[英]Join query retrieving data from only one table cakephp 3

I am new to cakephp. 我是Cakephp的新手。 I am usign query builder to fetch details from two tables using join in cakephp query builder.But the query i am writing is fetching details only from one table. 我是优缺点的查询构建器,使用cakephp查询构建器中的join从两个表中获取详细信息。但是我正在编写的查询仅从一个表中获取详细信息。 Need help to get data from other table as well. 还需要帮助以从其他表获取数据。

This is my code to fetch data by joining two tables: 这是我的代码,用于通过联接两个表来获取数据:

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);
}

As a result i am getting only details from events table. 结果,我只从事件表中获取详细信息。 But i need data from coursetype also.Any help is appreciated. 但是我也需要来自课程类型的数据。任何帮助表示赞赏。 Thank you. 谢谢。

Manually adding joins won't cause any additional data to be selected, you'd have to do that on your own by specifying the fields to be selected via the select() method. 手动添加联接不会导致选择任何其他数据,您必须自己自行完成操作,方法是通过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', /* ... */])
    // ...

I'd suggest to use use containments instead, ie setup the required association if not already present, and then simply use contain() : 我建议改用use包含,即设置所需的关联(如果尚未存在),然后简单地使用contain()

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

See also 也可以看看

您的解决方案在这里: CakePHP使用JOIN查找方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM