CakePHP:如何使用内部联接从两个表中检索数据?

555*_*nam 2 php mysql sql cakephp

我在数据库中有两个表,一个作为user(id,first_name,last_name),另一个作为location(id,country).

我需要根据条件对这两个表执行内连接,user.id = location.id查询结果应该包含列first_name,last_namecountry.

我在CakePHP中尝试了以下查询:

$this->set('users', $this->User->find('list', array(
    'fields' => array(
        'User.id',
        'User.first_name',
        'location.country'
    ),
    array(
        'joins' => array(
            array(
                'table' => 'location',
                'alias' => 'location',
                'type' => 'INNER',
                'conditions' => array('User.id = location.id')
            )
        )
    )
)));
Run Code Online (Sandbox Code Playgroud)

但是会产生这个错误:

'字段列表'中的未知列'location.country'

可能是什么问题呢?

AgR*_*zzo 5

我认为你的语法是错误的,因为options数组应该有一个连接键.你似乎有一个额外的array.尝试:

$this->set('users',$this->User->find('list', 
  array(
       'fields' => array('User.id', 'User.first_name','location.country'),
       'joins' => array(array('table' => 'location',
                               'alias' => 'location',
                               'type' => 'INNER',
                               'conditions' => array('User.id = location.id')
                         ))
         )
  ));
Run Code Online (Sandbox Code Playgroud)