I have two models:
posts
class posts extends Eloquent
{
public $timestamps = false;
protected $table = 'links';
public function commented()
{
return $this->hasMany('App\Models\comments','post_id')->where('reply',true);
}
}
comments
class comments extends Eloquent
{
public $timestamps = false;
protected $table = 'comments';
}
And data in tables is like that:
post data
{
"_id" : ObjectId("58837a559caf2fc968adc64d"),
"post_title" :'xyz'
}
{
"_id" : ObjectId("58837a559c6as77777as"),
"post_title" :'abc'
}
comments data
{
"_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'
}
Now I want to get all posts that contain count of comments (which reply=true) is greater than 0. Thanks.
An update of Alexey Mezenin's answer.
Post::has('commented')->whereHas('comments', function($query) {
$query->where('reply', '=', true);
})->get();
Use the has()
method:
Post::has('commented')->get();
This will get all posts that have at least one commented
relation.
Try this. Get all posts and then access every post to search for the once who have true as a reply:
$posts = Post::get()
$array = '';
foreach ($posts as $post) {
if ($post->commented->reply == True) {
$record = $post;
$array[] = $record;
}
}
return $array;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.