1

Assume a following example:

I got table of cars, their owners and a table of their types.

table cars: id, owner_id, type_id

table types: name, description

I want to get all types, whose id is NOT in type_id in table cars AND their owner_id IS 1.

I pass owner from the view and I tried the following:

public function show(Owner $owner)
    {

        $cartypes =CarTypes::all()->whereNotIn('id', function($query) { $query->table('cars')->select('type_id')->where('owner_id', '=', $owner->id); })->get();



        return view('sections.cars.show',compact('owner','cartypes'));


    }

But get Error: Method Illuminate\Database\Query\Builder::table does not exist.

Is my query fine? Can someone help me fix my query to get desired result?

1 Answer 1

1

You can use whereDoesntHave to get all types which are not in cars table where owner id is 1

$owner_id = 1;

CarTypes::whereDoesntHave('cars', function ($query) use ($owner_id) {
    $query->where('owner_id', '=', $owner_id );
})->get();

Querying Relationship Absence

Make sure your CarTypes model has mappings for cars

public function cars(){
    return $this->hasMany('App\Cars', 'type_id');
}
Sign up to request clarification or add additional context in comments.

1 Comment

You are my hero.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.