【发布时间】:2017-02-10 08:13:08
【问题描述】:
我在 Yii api 中有 Post、Comment 和 User。查询帖子时,结果应该是帖子数据、发布帖子的用户以及该帖子的任何评论,以及发布评论的用户以及完整的用户数据。
Comment 表包含一个 created_by 字段,它是 User 表中的 user_id。
要获得一个帖子,这里是控制器:
public function actionView($id){
$post = Post::find()
->innerJoinWith('user')
->joinWith('comments')
->where(['{{post}}.id' => $id])
->asArray()
->one();
return $post;
}
这会返回一个按 id 的帖子和任何评论。
获取所有帖子:
public function actionIndex(){
$posts = Post::find()
->joinWith('user', $eager)
->joinWith('comments', $eager)
->orderBy('updated_at DESC')
->limit(self::MAX_ROWS)
->asArray()
->all();
return $posts;
}
在 Post 模型中,Comment 关系是这样设置的:
public function getComments()
{
return $this
->hasMany(Comment::className(), ['object_id' => 'id']);
}
因此,如果有评论,这将返回评论,但不是每个评论的用户的完整用户数据。所以我把这个添加到getComments()
->joinWith('user u2','u2.id = comment.created_by')
除了评论之外,它确实会返回用户数据,但现在 actionIndex() 只返回有评论的帖子。
我查看了this SO question,但没有找到解决方案。如何有条件地将 joinWith 仅包含在带有评论的帖子中?
【问题讨论】: