M
M
MaxSemenov2021-09-20 10:42:39
Laravel
MaxSemenov, 2021-09-20 10:42:39

Why doesn't eager load fetch condition work in Laravel?

Hello everyone, I'm trying to make a selection with a connected model

ProductCategory::with(['domains' => function ($query) {
    $query->where('title', 'like', '%czechpartyking.de%');
}])->toSql();

but the condition does not work, and the query comes out like this if you apply the toSql () method
"select * from `product_categories` where `product_categories`.`deleted_at` is null"

although if you make a typo in the condition, it knocks out an error with a normal request
select `domains`.*, `domain_category_pivot`.`category_id` as `pivot_category_id`, `domain_category_pivot`.`domain_id` as `pivot_domain_id` from `domains` inner join `domain_category_pivot` on `domains`.`id` = `domain_category_pivot`.`domain_id` where `domain_category_pivot`.`category_id` in (5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28) and `ame` = czechpartyking.de

and if you paste it into the mysql console everything works

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
pLavrenov, 2021-09-20
@MaxSemenov

Returns extra, even those records that have no connection

Should I use whereHas()?
With even by the name says that the main query is returned but with relationship records that match the conditions. If there are no such relations, then it will return without relations.

A
Alexey Ukolov, 2021-09-20
@alexey-m-ukolov

The with method generates a separate query that will be executed after receiving the results of the main one, so toSql does not return it either. Install Debugbar or Telescope and see requests there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question