Laravel有许多关系复杂的查询

时间:2017-01-30 11:52:37

标签: php mongodb laravel eloquent laravel-5.3

我有两种模式:

  

帖子

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。 感谢。

3 个答案:

答案 0 :(得分:1)

Alexey Mezenin的回复更新。

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

答案 1 :(得分:0)

使用has()方法:

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

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

答案 2 :(得分:0)

试试这个。 获取所有帖子,然后访问每个帖子以搜索曾经有真实答复的人:

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