Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

243
Views
Laravel has many relationship complicated query

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.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

An update of Alexey Mezenin's answer.

Post::has('commented')->whereHas('comments', function($query) {
    $query->where('reply', '=', true);
})->get();
over 4 years ago · Santiago Trujillo Report

0

Use the has() method:

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

This will get all posts that have at least one commented relation.

over 4 years ago · Santiago Trujillo Report

0

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;
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!