staudenmeir / eloquent-has-many-deep

Laravel Eloquent HasManyThrough relationships with unlimited levels
MIT License
2.67k stars 157 forks source link

loadCount don't work correctly with withTrashed-columns #114

Closed nickurt closed 3 years ago

nickurt commented 3 years ago

Hey!,

The loadCount-function don't work with withTrashed because those columns will be not removed from the QueryBuilder

class QuxController extends Controller
{
    public function show(Qux $qux)
    {
        $qux->loadCount('fooBarBaz');
    }
}

class Qux extends Model
{
    use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
    use \Illuminate\Database\Eloquent\SoftDeletes;

    public function fooBarBaz()
    {
        return $this->hasManyDeep(Foo::class, [Bar::class, Baz::class], ['qux_id', 'baz_id', 'bar_id'], ['id', 'id', 'id'])
            ->withTrashed(['bar.deleted_at', 'baz.deleted_at']);
    }
}

will generate a query like this

select `id`, 
    (select count(*) from `foo` 
        inner join `bar` on `bar`.`id` = `foo`.`bar_id` 
        inner join `baz` on `baz`.`id` = `bar`.`baz_id` 
        where `bar`.`deleted_at` is null and `baz`.`deleted_at` is null and `qux`.`id` = `baz`.`qux_id`
    ) as `foo_bar_baz_count` 
from `qux` where `qux`.`id` in (?)

while I expected the bar.deleted_at and baz.deleted_at should be deleted just like the with function is doing ...

Is there a way to solve this?

staudenmeir commented 3 years ago

I'll look into it.

hasnat-we commented 3 years ago

@nickurt I found sadly that, Laravel removes additional constraints like 'distinct' clause from the relationship query when we use the relation in eager count. Seems like Laravel also removes 'withTrashed' clause.

staudenmeir commented 3 years ago

I released a new version that fixes this issue.