Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

245
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda