How to get records from a table when there is no relationship with another table in Laravel?

Asked

Viewed 164 times

3

In Laravel, when I want to get data from a table that contains some relationship, or when I want to get the data from a condition of a related table, for example, usuarios that contains livros, I use the method has or whereHas.

Thus:

 Usuario::has('livros')->get();

Or so:

 Usuario::whereHas('livros', function ($query)
 {
      $query->where('titulo', '=', 'Harry Potter');
 })->get();

But now I need the reverse situation.

I want to capture only users who don’t have relationships with Livros.

I want to capture only users who don’t compare relationships with books from Harry Potter.

How can I do it in the Laravel?

1 answer

2


Since no one answered, I answer.

Just use the methods doesntHave and whereDoesntHave.

For example, I want all usuários which do not possess the nível 'admin', both of whom have a relationship N:N.

$usuarios = Usuario::whereDoesntHave('niveis', function ($query)
{
     $query->where('nome', '=', 'admin');

})->get();

If I want now only users who have no relationship with niveis, then we can simply use doesnHave

  Usuario::doesntHave('niveis')->get();

In that reply in English, there are also some examples that I put there.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.