我有一个带有休息API的yii应用程序。我想获得一个包含该帖子的所有注释以及该帖子创建者的用户对象的帖子对象。
同样在评论中,我希望每个发表评论的用户都有一个用户对象。
因此,一个帖子包含帖子用户,每个帖子都有很多评论。
服务api请求的后控制器如下所示:
public function actionIndex(){
$post = Post::find()
->joinWith('user)
->joinWith('comments')
->asArray()
->all();
}
return $post;
然后为用户模型和注释:
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'created_by'])->innerJoinWith('profile p1');
}
public function getComments()
{
return $this->hasMany(Comment::className(), ['object_id' => 'id'])->leftJoin('user u2', 'u2.id = comment.created_by');
}
帖子的用户返回正常。返回评论。但是每个评论都没有返回的用户。我觉得getComments()方法中的左联接应该吸引用户。缺少了什么?
我回来像这样:
{
"id":"1",
"message":"this is a post",
"user":
[{
"id:11",
"name":"bob smith"
}],
"comments":
[{
"id:21",
"remark":"this is a comment"
}]
}
我想找回这个:
{
"id":"1",
"message":"this is a post",
"user":
[{
"id:11",
"name":"bob smith"
}],
"comments":
[{
"id:21",
"remark":"this is a comment",
"user":
[{
"id:41",
"name":"jane doe"
}]
}]
}
更新:如果我将
getComments()
从leftJoin
更改为innerJoinWith
像这样:public function getComments()
{
return $this->hasMany(Comment::className(), ['object_id' => 'id'])->innerJoinWith('user u2', 'u2.id = comment.created_by');
}
...然后我得到格式正确的输出,但它仅包含包含注释的帖子。
最佳答案
我尚未检查,但是您可以尝试:
$post = Post::find()
->joinWith('user')
->joinWith(['comments' => function($q) {
$q->joinWith(['user']);
}])
->asArray()
->all();
}