0
我在Yii api中有Post,Comment和User。當查詢帖子時,結果應該是發佈數據,發佈帖子的用戶以及該帖子的任何評論,以及發佈評論的用戶使用完整的用戶數據。如何在Yii中創建條件活動記錄關係
評論表包含一個created_by
字段,它是用戶表中的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模型,註釋關係是這樣設置:
public function getComments()
{
return $this
->hasMany(Comment::className(), ['object_id' => 'id']);
}
因此,這將返回意見,如果THRE是有,但不是完整的用戶每個評論用戶的數據。所以我說這getComments()
->joinWith('user u2','u2.id = comment.created_by')
這確實與評論一起返回用戶數據,除了....現在actionIndex()
僅返回評論文章。
我回顧了this SO question,但沒有找到解決辦法。我如何有條件地將joinWith
僅包含有評論的帖子?