我试图在cakephp中使用LEFT join来选择数据,这里我如何使用两个以上的表进行LEFT join.Here iam在两个表之间创建LEFT连接news_feeds和news_feed_likes.i想在这里引入另外两个表,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 ) );
答案 0 :(得分:3)
我的第一点建议是考虑将其移至模型中。但是,要回答具体问题,只需根据外键添加更多联接。因此,例如,如果您在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编码标准。它会让你的生活减轻痛苦。避免为模型使用小写的下划线别名。总是用CamelCase写一个大写的第一个字母和单数字。因此,在您的联接中,您应该使用newslikes
和newscommentslikes
而不是NewsLike
和NewsCommentLike
作为别名。
答案 1 :(得分:-1)
您可以使用以下语法连接多个表:
$this->paginate = array(
'conditions' => array(),
'joins' => array(
array(
'alias' => 'TableAlias1',
'table' => 'table_name_1',
'type' => 'LEFT',
'conditions' => array(
'TableName.id = table_name_1.id',
),
),
array(
'alias' => 'TableAlias2',
'table' => 'table_name_2',
'type' => 'LEFT',
'conditions' => array(
'TableName.id = table_name_2.id',
),
),
array(
'alias' => 'TableAlias3',
'table' => 'table_name_3',
'type' => 'LEFT',
'conditions' => array(
'TableName.id = table_name_4.id',
),
)
),
'fields' => array(),
'order' => array()
);