@PRodion

Как получить связанные данные одним запросом?

Есть:

class YarnController extends Controller
{
    public function show($manufacturer, $collection = null)
    {
        if (!$collection) {
            $collections = Collection::whereHas('manufacturer', function($query) use ($manufacturer) {
                $query->where('id', $manufacturer);
            })->get();
        } else {
            $collections = Collection::whereHas('manufacturer', function($query) use ($manufacturer) {
                $query->where('id', $manufacturer);
            })->where('id', $collection)->get();
        }

        return view('yarn', compact('collections'));
    }
}


И

@foreach ($collections as $collection)
    <p>{{ $collection->manufacturer->name }} - {{ $collection->name }}</p>
@endforeach


Получается:

select * from `collections` where exists (select * from `manufacturers` where `collections`.`manufacturer_id` = `manufacturers`.`id` and `id` = '2')
select * from `manufacturers` where `manufacturers`.`id` = 2 limit 1
select * from `manufacturers` where `manufacturers`.`id` = 2 limit 1
select * from `manufacturers` where `manufacturers`.`id` = 2 limit 1


Коллекции производителя выводятся за один запрос, но вот для получения производителя каждый раз делается новый запрос.
  • Вопрос задан
  • 157 просмотров
Решения вопроса 1
Fernus
@Fernus
Техник - Механик :)
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы