2016-08-19 18 views
0

我有一個yii應用程序,其餘api。我想獲得一個帖子對象,包括該帖子的所有評論以及帖子創建者的用戶對象。 同樣在評論中,我想爲每個留下評論的用戶提供用戶對象。Yii REST API - 在查詢中使用多個連接

因此,一個職位與發佈用戶和許多評論與用戶。

的柱控制器服務的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" 
     }] 
    }] 
} 

UPDATE:如果我改變getComments()leftJoininnerJoinWith這樣的:

public function getComments() 
{ 
    return $this->hasMany(Comment::className(), ['object_id' => 'id'])->innerJoinWith('user u2', 'u2.id = comment.created_by'); 
} 

...然後我得到格式正確的輸出,但它只包括包含評論的帖子。

+0

它實際上是從我的觀點是錯誤的。請閱讀 - http://www.yiiframework.com/doc-2.0/guide-rest-resources.html閱讀關於擴展部分和extraFields。 – ineersa

+0

@ineersa我讀過......不知道如何實現。如果你可以檢查,我添加了一些代碼。 – lilbiscuit

+0

在控制器動作中使用'with()'而不是'joinWith()',然後將'user'和'comments'添加到'extraFields',然後使用'expand =用戶,評論'到你的行動。在'getComments()'嘗試用'joinWith()'加載數據。應該做的伎倆。 – ineersa

回答

2

我沒有檢查,但你可以嘗試:

$post = Post::find() 
     ->joinWith('user') 
     ->joinWith(['comments' => function($q) { 
      $q->joinWith(['user']); 
     }]) 
     ->asArray() 
     ->all(); 
} 
+0

這隻會返回有評論的帖子。 – lilbiscuit

+0

你試過了嗎? joinWith產生了一個左連接,所以看起來很奇怪,它只返回帶有註釋的帖子。 –

+0

我試過但Active Record'joinWith'是一個內部連接,[不是左連接](http://www.yiiframework.com/doc-2.0/yii-db-activequery.html#relational-query)。 – lilbiscuit