Where NOT in pivot table

Submitted by wallacemaxters - 2 years ago

Get results in a table when there are no results for the relationship

// Simple query

User::doesntHave('Role')->get();

//SELECT * FROM users WHERE ((SELECT count(*) FROM roles WHERE user.role_id = roles.id) < 1)

// For complex query

$id = 1;
User::whereDoesntHave('Role', function ($query) use($id) {
      $query->whereId($id);
})
->get();

//SELECT * FROM users WHERE ((SELECT count(*) FROM roles WHERE user.role_id = roles.id and id = 1) < 1)

Ads cover the costs of maintaining Laravel-tricks

comments powered by Disqus

Ads cover the costs of maintaining Laravel-tricks