2017-01-30 19 views
1

た:表中のLaravelは、私は2つのモデル持っている多くの関係は複雑クエリ

投稿

class posts extends Eloquent 
{ 
public $timestamps = false; 
protected $table = 'links'; 

public function commented() 
{ 
    return $this->hasMany('App\Models\comments','post_id')->where('reply',true); 
} 
} 

コメント

class comments extends Eloquent 
{ 
public $timestamps = false; 
protected $table = 'comments'; 
} 

、データはそのようなものです:

ポストデータ

{ 
    "_id" : ObjectId("58837a559caf2fc968adc64d"), 
    "post_title" :'xyz' 
} 
{ 
"_id" : ObjectId("58837a559c6as77777as"), 
"post_title" :'abc' 
} 

コメントデータ

{ 
    "_id" : ObjectId("58837a559caf2fa6a8s0v0z"), 
    "post_id" :'58837a559caf2fc968adc64d' 
    "reply":true, 
    "comment":'1st comment' 
} 
{ 
"_id" : ObjectId("58837a55z7asd09zx865v9"), 
"post_id" :'58837a559c6as77777as', 
"reply":false, 
"comment":'comment' 
} 
{ 
    "_id" : ObjectId("58837a559caf2fa6a8s0v0z"), 
    "post_id" :'58837a559caf2fc968adc64d' 
    "reply":true, 
    "comment":'2nd comment' 
    } 

は、今私は大きい(=真の返信)コメントの数が含まれているすべての記事を取得したいですありがとうございます。 ありがとうございます。

Post::has('commented')->get(); 

これは、少なくとも1体のcommented関係を持っているすべての記事を取得します:

答えて

1

アレクセイ・メゼニンの答えが更新されました。

Post::has('commented')->whereHas('comments', function($query) { 
    $query->where('reply', '=', true); 
})->get(); 
0

has()メソッドを使用します。

+0

感謝@Alexey Mezenin。 しかし、私は答えが本当であるというコメントだけを得たいと思っています。 –

0

これを試してください。 すべての記事を取得して、応答として真の持っている一度に検索するために、すべての記事にアクセス:

$posts = Post::get() 
$array = ''; 
foreach ($posts as $post) { 
     if ($post->commented->reply == True) { 
      $record = $post; 
       $array[] = $record; 
      } 
} 
return $array; 
関連する問題