Laravel with с перебором
Мне нужно выбрать все модели model1 где not_needle_id в model2 не совпадает с передаваемым параметром. model2 - связан с model1 и отображается при дебаге...
$plans = $section->model1()->with(['model2' => function ($q) use ($notNeedle) {
$q->where('not_needle_id', '<>', $notNeedle->id);
}])->active()->get();
Но почему то $q->where('not_needle_id', '<>', $notNeedle->id); - просто игнорируется....
Вот строка SQL запроса
"select * from `model1_table` where `model1_table`.`section_id` = ? and `model1_table`.`section_id` is not null and `status` = ? and `model1_table`.`deleted_at` is null"
Как мне быть?
Ответы (1 шт):
Автор решения: Daniel Protopopov
→ Ссылка
Нужно вот так:
$plans = $section->model1()->with(['model2'])->whereHas('model2', function ($q) use ($notNeedle) {
$q->where('not_needle_id', '<>', $notNeedle->id);
}])->active()->get();
whereHas определяет количество связей, и на присутствие отношения. Можно и просто через where.