如何在Yii中建立条件活动记录关系
我在Yii api中有帖子、评论和用户。查询帖子时,结果应该是帖子数据、发表帖子的用户、该帖子的任何评论,以及使用完整用户数据发表评论的用户 注释表包括一个由创建的如何在Yii中建立条件活动记录关系,yii,yii2,Yii,Yii2,我在Yii api中有帖子、评论和用户。查询帖子时,结果应该是帖子数据、发表帖子的用户、该帖子的任何评论,以及使用完整用户数据发表评论的用户 注释表包括一个由创建的字段,该字段是用户表中的用户id 要获得单个Post,以下是控制器: public function actionView($id){ $post = Post::find() ->innerJoinWith('user') ->joinWith('comments')
字段,该字段是用户表中的用户id
要获得单个Post,以下是控制器:
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']);
}
因此,如果有注释,则返回注释,但不是每个注释用户的完整用户数据。所以我把它添加到getComments()
它会返回用户数据和注释,除了。。。。现在actionIndex()
只返回有注释的帖子
我检查了一下,但没有找到解决办法。我如何有条件地将joinWith
仅包含在带有注释的帖子中?我建议您使用->with()
而不是joinWith()
:
这样,您只需使用本应在Post
model类中声明的关系。在此之后,还要将->with()
添加到注释中关系声明中的Post
模型类:
public function getComments() {
return $this
->hasMany(Comment::className(), [
'object_id' => 'id',
])
->with('user');
}
这样,你就可以得到所有的帖子,用户和他们自己的用户的评论
public function actionIndex() {
$posts = Post::find()
->with('user')
->with('comments')
->orderBy('updated_at DESC')
->limit(self::MAX_ROWS)
->asArray()
->all();
return $posts;
}
public function getComments() {
return $this
->hasMany(Comment::className(), [
'object_id' => 'id',
])
->with('user');
}