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

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 in a related table, for example, usuarios containing livros , I use the methods has or whereHas .

So:

 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 do not have relationships with Livros .

I want to capture only users who do not have relationships with Harry Potter books.

How can I do this in Laravel?

    
asked by anonymous 06.05.2016 / 22:50

1 answer

2

Since no one answered, I answer.

Just use the methods doesntHave and whereDoesntHave .

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

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

})->get();

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

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

In this answer , there are also some examples that I I put it there.

    
10.05.2016 / 18:40