I have a problem with retrieving the data from Users table:
User:
-id int
-name string
-compartment_id int
This is related with compartments
table:
Compartment:
-id int
-name string
-country_id int
Which is related to countries
table:
Country:
-id int
-name string
User model:
public function compartment()
{
return $this->belongsTo(Compartment::class, 'compartment_id');
}
Compartment model:
public function country()
{
return $this->belongsTo(Country::class, 'country_id');
}
public function users()
{
return $this->hasMany(User::class);
}
Country model:
public function compartments()
{
return $this->hasMany(Compartment::class);
}
I am using Livewire PowerGrid to display data in data tables.
I wanted to get All Users with compartment_id
= null
and All Users that compartment->country_id
is equal to Auth::user()->compartment->country_id
.
I’m stuck with:
User::whereIn('compartment_id', Compartment::select('country_id')
->where('country_id', Auth::user()->compartment->country_id))->where('compartment_id', null);
It must be the builder, without ->get()
because it’s interpreted by PowerGrid correctly.
Can someone instruct?
2
Answers
I found the solution by myself.
I thought wrongly (by mistake) that it should be
AND
clause, notOR
. Thanks all for help.You can use the below query,
You will get all users without compartment assigned and those whose compartment country matches with compartment