2016-09-12 4 views
1

データベースに3つのテーブルがあります(つまり、投稿、コメント、好きなようなもの)。 Comments and Likesでこれらの投稿を取得したいしかし、ユーザーがコメントや好きな投稿を投稿するだけです。ユーザーがコメントや好きでない場合は、投稿を取得しないでください。別の関係で条件付きデータを取得する方法を知っています。しかし、私はどのように私がORで関係を結ぶことができるかを知ることはできません。誰かが答えを知っていれば、それは感謝されます。laravelの複数の関係に関する条件

ここに私の個人的な関係の条件のコードです。

$this->posts = Post::with(['comments', 'votes']); 
if($field == 'comments') { 
    $this->posts->whereHas('comments', function($query) 
     { 
      $query->where('in_user_id', Auth::user()->in_user_id); 
     }); 
} else if ($field == 'votes') { 
    $this->posts->whereHas('votes', function($query) 
     { 
      $query->where('in_user_id', Auth::user()->in_user_id); 
     }); 
} else if($field == 'both') { 
    // Here I want help 
} 

答えて

0

これは私の間違った焦点でした。私は$query->where()にしか集中しませんでした。しかし、それは簡単でした。投票のためにwhereHas()orWhereHas()に変更するだけです。

ここは更新された(解決策)コードです。

$this->posts = Post::with(['comments', 'votes']); 
if($field == 'comments') { 
    $this->posts->whereHas('comments', function($query) 
     { 
      $query->where('in_user_id', Auth::user()->in_user_id); 
     }); 
} else if ($field == 'votes') { 
    $this->posts->whereHas('votes', function($query) 
     { 
      $query->where('in_user_id', Auth::user()->in_user_id); 
     }); 
} else if($field == 'both') { 
    $this->posts->whereHas('comments', function($query) 
     { 
      $query->where('in_user_id', Auth::user()->in_user_id); 
     }); 
    $this->posts->orWhereHas('votes', function($query) 
     { 
      $query->where('in_user_id', Auth::user()->in_user_id); 
     }); 
} 
関連する問題