2017-02-09 96 views
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僅包含有評論的帖子?

回答

0

我會建議你使用->with(),而不是joinWith()

public function actionIndex() { 
    $posts = Post::find() 
     ->with('user') 
     ->with('comments') 
     ->orderBy('updated_at DESC') 
     ->limit(self::MAX_ROWS) 
     ->asArray() 
     ->all(); 

    return $posts; 
} 

這樣,你只需要使用你已經應該在你的Post模型類已宣佈的關係。在此之後,還可以添加->with()comments關係的聲明在Post模型類:

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

這樣,你應該得到的所有帖子,用戶和評論與自己的用戶。