[英]Yii REST API - using multiple joins in query
我有一個帶有休息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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.