mercredi 22 février 2023

Laravel withTrashed in related model query callback

I am working with an old Laravel 5.7 app, and I'm having a nightmarish issue with fetching trashed related models with a callback function.

My setup is as follows:

$filter_comments = function ($q) use ($parameters) {
$q->whereBetween('dated_at', [$parameters['start'], $parameters['end']]);
$q->where('special_post', 1);
$q->whereIn('image_id', $parameterss['image_list']);
$q->withTrashed();
};

$collection = Post::with(['comments' => $filter_comments]);

The query with its filter works just fine except for the $q->withTrashed() line.

If I dump its internal SQL ($q->toSql() inside the callback function), I can see a blatant contradiction being inserted in my query. Whenever I add the withTrashed() line, Laravel appends a AND 0 = 1 to my query.

select * from `comments` where `comments`.`image_id` in (1,2,3) and `dated_at` between ? and ? and `special_post` = ? and 0 = 1

Both models have correctly defined belongsTo() and hasMany() relationships, and display no other issues. I have also tried adding withTrashed() to the relationship deffintion in the respective model file, but it didn't work either.

I am aware of some related bugs with previous Laravel versions (https://github.com/laravel/framework/issues/11860) but as far as I know, they are fixed for Laravel 5.7

I would really appreciate some feedback!

Thanks in advance!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire