问题
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