How to perform a consultation in the bank applying "exceptions" with a relationship?

Asked

Viewed 121 times

1

I need to get all users with "Exceção" those of the function containing the id=2, it is possible?

You can fit a Where in that consultation?

I have the following consult at the bank Laravel which returns an object to the datatables.net follow-up consultation:

$query = User::query()->select('*');
$query->with(['roles']);
$table = Datatables::of($query);

This returns me all the users of the bank and with their respective functions 'roles'. if I want to fetch everyone from a certain function I do it:

$query = Role::find(1)->users;
$table = Datatables::of($query);

The '1' within find() represents the id of function

find(1)

but I need to get all users of all functions Except that of the id = 2 it is possible?

  • the functions of Roles ???

  • 1

    yes, the way it is in the example

  • Take a look at this query: $query = User::query()->select('*'); $query->with(['roles']); it returns to me all users of all Roles but I want it to return all users except those of role 1

1 answer

2


You can do it like this:

All the Role except for the number 2 bring the relationship of usuários, example

$users = Role::where('id', '<>', 2)->users;

bringing all users except what has roles == 2.

Observing: users and its relationship with the functions of each user so put the same name configured in your model

Another way by the user’s relationship with the method has():

$users = User::with(['roles'])->has('roles', '<>', 2)->get();

Reference: Querying Relationship Existence

  • 1

    That was it! Thank you!!

  • Dude, I tested and your method didn’t work.

  • Take a look at this query: $query = User::query()->select('*'); $query->with(['roles']); it returns to me all users of all Roles but I want it to return all users except those of the role 1

  • @Rafael Voce did the same in my example, can not separate?

  • @Rafael is a Builder if he cannot separate because there he does not guard the state as it should. Pay attention to my example...

  • Sorry@Virgilio Novic but still no intender :/

  • @Rafael can not separate the commands is equal is in the answer. Understood?

  • I understood, I did it but it didn’t work. it returned me all users. of all functions "roles" and in my case I wanted to take the Role with ID 1

  • @Rafael works yes you’re doing something wrong. Edit your question and ask what you did. It works yes.

  • Remove query() @Rafael can’t have this guy there the question has been edited

  • @Rafael I made a minimal example and that’s right ... If you have any problem edit your question explaining the step by step you did it ... Here on the site has already been answered a way to debug the generated SQL: https://answall.com/questions/148766/como-ver-as-queries-que-foram-executed

Show 6 more comments

Browser other questions tagged

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