2017-01-30 78 views
1

我有两个型号:Laravel有许多关系复杂的查询

帖子

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' 
    } 

现在我想包含的注释计数的所有帖子(其中回复= TRUE)大于比0. 谢谢。

回答

1

Alexey Mezenin的回答更新。

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

使用has()方法:

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

这将获得至少有一个commented关系中的所有帖子。

+0

谢谢@Alexey Mezenin。 但我只想得到那个回复是真的评论。 –

0

试试这个。 获取所有帖子,然后访问每一个帖子,寻找曾作为答复的人:

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