cakephp - 在 cakephp 中创建左连接

标签 cakephp

我正在尝试在 cakephp 中使用 LEFT join 选择数据,在这里我如何使用两个以上的表进行 LEFT join。这里我在两个表 news_feeds 和 news_feed_likes 之间创建 LEFT join。我想在这里再介绍两个表,NewsFeedComments和 newsfeed_likes_comments。我该怎么做?

谢谢你的帮助

$this->paginate = array(
    'conditions' => array('NewsFeed.group_id'=>$groupdata['Group']['id'],'NewsFeed.status'=>'A'),
    'joins' => array(
        array(
            'alias' => 'newslikes',
            'table' => 'news_feed_likes',
            'type' => 'LEFT',
            'conditions' => array(
                'newslikes.news_feed_id = NewsFeed.id',
                'newslikes.user_id'=>$this->Auth->user('id'),
                'newslikes.status'=>'1',
            ),
        ),
        array(
            'alias' => 'newscommentslikes',
            'table' => 'news_feed_comments_likes',
            'type' => 'LEFT',
            'conditions' => array(
                'newscommentslikes.news_feed_comment_id = NewsFeedComment.id',
                'newscommentslikes.user_id'=>$this->Auth->user('id'),
                'newscommentslikes.status'=>'1',
            ),
        ),
    ),
    'fields' => array(
        'IFNULL(newslikes.user_id,0) AS likestatus', 
        'NewsFeed.id', 
        'NewsFeed.posted_message', 
        'NewsFeed.created', 
        'NewsFeed.user_id', 
        'NewsFeed.status', 
        'NewsFeed.newslike', 
        'IFNULL(newslikes.status,0) AS status',
     ),
    'order' => array('NewsFeed.created' => 'desc'),
);

$this->set('newsfeed', $this->paginate( $this->NewsFeed ) );

最佳答案

我的第一个建议是考虑将其移至模型中。但是,要回答具体问题,只需根据外键添加更多连接即可。因此,例如,如果您在 NewsFeedLike 和 NewsFeedLikeComments 之间有一个外键,您可以像这样添加另一个连接:

'joins' => array(
    array(
        'table' => 'news_feed_like_comments',
        'alias' => 'NewsFeedLikeComment',
        'type' => 'LEFT',
        'conditions' => array(
            'NewsFeedLikeComment.news_feed_like_id = NewsFeedLike.id',
        ),
    ),

因为您已经加入 NewsFeedLike,它会使用这些条件来限制 NewsFeedLikeComment。

另一个提示:在编写代码时始终遵循 CakePHP 编码标准。它会让你的生活少很多痛苦。避免为模型使用带下划线的小写别名。总是用首字母大写和单数写成驼峰命名法。因此,在您的联接中,您应该使用 NewsLikeNewsCommentLike,而不是 newslikesnewscommentslikes 作为别名。

关于cakephp - 在 cakephp 中创建左连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20571806/

相关文章:

php - CakePHP 执行此操作的正确方法(从设置表中获取值)

cakephp - 我什么时候应该在 cakephp 1.3 中使用 app/libs?

php - CakePHP 站点主页的 Time to First Byte 很长

javascript - 无法调用jquery函数在cakephp 3中工作

cakephp - 保存与 Cakephp 3 的关联

apache - 如何在 cakephp 2 中添加 header 过期

php - Azure Web 应用程序上的 Cakephp 2.5

ruby-on-rails - CakePHP 是否以 Ruby on Rails 为模型?

php - CakePHP:如何在模型中访问 $this->request

javascript - 如何使用 Angular 将表单数据发送到服务器?