[英]Only one table's datas selected when join two tables in cakephp
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? 我的代码中是否有任何错误?
You need to move the 'fields'
option out of 'joins'
. 您需要将
'fields'
选项从'joins'
移出。 Otherwise $this->find will only fetch the fields for the current model. 否则,$ this-> find将仅获取当前模型的字段。 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. 记住,当您指定
'fields'
时,添加您需要的所有字段,既包括当前模型'fields'
,又包括您要加入的表中的字段。
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;
Try to use reucrsive 2 and you have to relation the table into your moedl correctly if you want to retrieve your data. 尝试使用reucrsive 2,如果要检索数据,则必须将表正确关联到模块中。 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
查询后,您可以拥有一个包含所有字段的大数组,请尝试使用var_dump打印以查看是否拥有所需的所有字段
$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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.