Only one table's datas selected when join two tables in cakephp

旧巷老猫 提交于 2020-01-16 03:30:30

问题


I used this code, but only one table's data selected.

I need to select all fields from two tables:

$options['joins'] = array(
                array('table' => 'tbl_users',
                    'alias' => 'Users',
                    'type' => 'INNER',
                    'foreignKey' => 'assigned_by',
                    'fields' => 'Users.user',
                    'conditions' => array(
                        'TravancoAdmin.assigned_by = Users.id'
                    )
                )
            );
            $options['conditions'] = array( 'TravancoAdmin.id' => $task_id);
$result = $this->find('all', $options);
        return $result ? $result : 1;

How can i get all fields from two tables?

If there is any mistakes in my code?


回答1:


You need to move the 'fields' option out of 'joins'. Otherwise $this->find will only fetch the fields for the current model. Remember to add all fields you need when you specify 'fields', both the ones for the current model and the ones you need from the table you're joining.

For example:

$options['joins'] = array(
                array('table' => 'tbl_users',
                    'alias' => 'Users',
                    'type' => 'INNER',
                    'foreignKey' => 'assigned_by',
                    // 'fields' => 'Users.user', <- get rid of this
                    'conditions' => array(
                        'TravancoAdmin.assigned_by = Users.id'
                    )
                )
            );
$options['fields'] = array('TheModelThatThisRefersTo.*','Users.user'); // <- insert this
$options['conditions'] = array( 'TravancoAdmin.id' => $task_id);
$result = $this->find('all', $options);
return $result ? $result : 1;



回答2:


Try to use reucrsive 2 and you have to relation the table into your moedl correctly if you want to retrieve your data. After you the query you can have a big array with all fields, try to print with a var_dump to see if you have all your fields that you want

$this->recursive = 2;
$options['joins'] = array(
                array('table' => 'tbl_users',
                    'alias' => 'Users',
                    'type' => 'INNER',
                    'foreignKey' => 'assigned_by',
                    'fields' => 'Users.user',
                    'conditions' => array(
                        'TravancoAdmin.assigned_by = Users.id'
                    )
                )
            );
            $options['conditions'] = array( 'TravancoAdmin.id' => $task_id);
$result = $this->find('all', $options);
        return $result ? $result : 1;


来源:https://stackoverflow.com/questions/12406081/only-one-tables-datas-selected-when-join-two-tables-in-cakephp

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