P
P
Prodion2021-03-28 12:49:59
Laravel
Prodion, 2021-03-28 12:49:59

How to get related data in one request?

There is:

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'));
    }
}


And

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


It turns out:

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


Producer collections are displayed in one request, but a new request is made each time to get the producer.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
N, 2021-03-28
@PRodion

Collection:: with('manufacturer') ->whereHas...
https://laravel.com/docs/8.x/eloquent-relationship...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question