staudenmeir / belongs-to-through

Laravel Eloquent BelongsToThrough relationships
MIT License
1.15k stars 88 forks source link

belongsToThrough does not take withTrashed into account when using in combination with whereHas #68

Closed RenoLooijmans closed 2 years ago

RenoLooijmans commented 2 years ago

I have the following relationship:

Organisation > Event > Channel > Order

In model Order.php, the following relationship is defined.

public function organisation(): \Znck\Eloquent\Relations\BelongsToThrough
    {
        return $this->belongsToThrough(Organisation::class, [Event::class, Channel::class])
            ->withTrashed('channels.deleted_at', 'events.deleted_at')
            ->withTrashed();
    }

When the function is called like:

Order::query()
    ->has('organisation')
    ->toSql();

It completely ignores the withTrashed methods, as the query returned is:

"select * from `orders` where exists (select * from `organisations` inner join `events` on `events`.`organisation_id` = `organisations`.`id` inner join `channels` on `channels`.`event_id` = `events`.`id` where `channels`.`id` = `orders`.`channel_id` and `events`.`deleted_at` is null and `channels`.`deleted_at` is null) and `orders`.`deleted_at` is null"

If in the model Order.php I remove the withTrashed methods, the following query is returned (please note the double deleted_at selectors).

"select * from `orders` where exists (select * from `organisations` inner join `events` on `events`.`organisation_id` = `organisations`.`id` inner join `channels` on `channels`.`event_id` = `events`.`id` where `channels`.`id` = `orders`.`channel_id` and `events`.`deleted_at` is null and `channels`.`deleted_at` is null and `events`.`deleted_at` is null and `channels`.`deleted_at` is null and `organisations`.`deleted_at` is null) and `orders`.`deleted_at` is null"

Expected query result with the withTrashed methods used:

"select * from `orders` where exists (select * from `organisations` inner join `events` on `events`.`organisation_id` = `organisations`.`id` inner join `channels` on `channels`.`event_id` = `events`.`id` where `channels`.`id` = `orders`.`channel_id`) and `orders`.`deleted_at` is null"

Laravel v9.3.1. BelongsToThrough v2.12.

staudenmeir commented 2 years ago

I released a fix.

RenoLooijmans commented 2 years ago

Thanks for the quick turnaround of the fix - it's working!