Abdus Sattar Bhuiyan
Abdus Sattar Bhuiyan

Reputation: 3074

Where not in with a belongs to relationship in laravel

I have two table named 'districts' & 'division' as follows:

division table

enter image description here

districts table

enter image description here

division model hasMany districts

Now I want to get all division with districts except some districts. I am trying as follows:

$divisionWithDistricts = Division::with('districts')->whereNotIn('districts.id',$districtsAlreadyUsed)->get();

Here districtsAlreadyUsed is an array of district ids. I got Unknown column 'districts.id' error. It was so easy if district_id was present at division table. How can I get such data at this situation?

Upvotes: 0

Views: 243

Answers (1)

Donkarnash
Donkarnash

Reputation: 12845

Try this

$divisionWithDistricts = Division::with(['districts' => function($query) use($districtsAlreadyUsed) {
    $query->whereNotIn('id', $districtsAlreadyUsed);
}])
->get();

Upvotes: 1

Related Questions