M
M
Mikhail Nosov2018-12-04 06:52:00
Laravel
Mikhail Nosov, 2018-12-04 06:52:00

Laravel - how to write a greedy Eloquent query?

Need a greedy Eloquent query through models.
The models are already there: Pagetype, Page, Service and Category, and the pagetype_service table is created for the links.
The models already have the corresponding links with other models. You can also make new connections if necessary.

pagetypes
    id
    ru_name
    sef_name

pagetype_service
    id
    page_id
    pagetype_id
    service_id

pages
    id
    title
    h1
    ...

services
    id
    category_id
    sef_url
    price
    ...

сategories
    id
    parent_id
    sef_url
    ...

We need to get all pages from pages that match a certain type from the pagetypes table. I have a specific sef_name.
You need to get all pages, but which in the pagetype_service table have a pagetype_id equal to the corresponding id obtained by sef_name from the pagetypes table.
There, in the pagetype_service table, there is a service_id field - this is the connection of each page with the services table, and you need to get the corresponding data for each page
. And in the services table there is a category_id field, which is a connection with the categories table, and you need to get this data too.
Is it possible to do this in one request?
A greedy query is needed so that later separate queries do not appear when traversing the data in the foreach loop

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mikhail Nosov, 2018-12-04
@WebSEOkz

Thank you, I tried a bunch of options here, but I found a solution.
I got it like this:

$sefName = 'проверка';
$pages = Page::whereHas('pagetypes', function ($query)  use ($sefName) {
    $query->where('sef_name', $sefName);
})->with('services.category')->get();

A
Anton Mashletov, 2018-12-04
@mashletov

$sefName = 'проверка';
$pages = Page::whereHas('service', function($query) use ($sefName) {
  $query->whereHas('pageType', function($query) use ($sefName) {
    $query->where('sef_name', $sefName);
  })->with('pageType');
})->with('service')->get();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question