如何在CakePHP中编写连接查询?

时间:2013-04-26 08:52:19

标签: cakephp join cakephp-2.0

我有两张表postsuserspost.user_id=users.id

字段是

user: id, username, password
post: id, user_id, post_name

我想select post.id, post.post_name, user.username

如何在CakePHP中选择它?

我有两个名为UserPost的模型。它从PostController调用模型。

2 个答案:

答案 0 :(得分:3)

如果你有correctly defined the relationship between those two models,那么当你使用Post模型的find方法时就会发生这种情况:

// In PostsController
$posts = $this->Post->find('all');

// $posts should be an array like this
Array
(
    [0] => Array
        (
            [Post] => Array
                (
                    // Model data
                )
            [User] => Array
                (
                    // Model data
                )
        )
)

希望这有帮助。

答案 1 :(得分:2)

您应该正确定义两个模型之间的关系以简化您的生活,但是如果您想使用连接,这里是语法:

find('all', array(
        'conditions' => array('name' => 'Thomas Anderson'),
        'joins' => array(
            array(
                'alias' => 'Thought',
                'table' => 'thoughts',
                'type' => 'LEFT',
                'conditions' => '`Thought`.`person_id` = `Person`.`id`'
            )
        )
 ));