Select all soft deleted item which owner is not so

2020-05-06 08:20发布

问题:

I have a query to get all soft delete tournaments:

 $tournaments = Tournament::onlyTrashed();

Thing is Tournament model has a FK owner_id.

Sometimes, owner has been soft deleted, so when I try to get $tournament->owner->id, I get an exception.

How to get All trashed Tournament which user is not soft deleted in Eloquent???

Is there a more elegant (Eloquent) solution that :

 $tournaments = Tournament::onlyTrashed()
            ->join('users', 'users.id', '=', 'tournament.user_id')
            ->where('users.deleted_at', '=', null)
            ->select('tournament.*')
            ->get();

Tx!

回答1:

has and whereHas (for more complex relationship requirements) can be used to limit results to records that have an active relationship.

Tournament::has('Owner')

will select only tournaments with a valid (existing and non-soft-deleted) Owner.