C
C
chelkaz2016-03-25 17:48:12
Laravel
chelkaz, 2016-03-25 17:48:12

Link requests. Am I wrong or does it make a difference?

The documentation says (judging by what I understood from the translation)
https://laravel.com/docs/5.2/eloquent-relationships
That the number of requests decreases tenfold if you use the with method :

Thankfully, we can use eager loading to reduce this operation to just 2 queries. When querying, you may specify which relationships should be eagerly loaded using the with method:

----------
But in my example:
$adboard = Board::with('user', 'category', 'currency', 'getPhoto')->orderBy('created_at','desc')->paginate(15);

What is so 8 queries with with method :
select count(*) as aggregate from `boards` 270μs
select * from `boards` order by `created_at` desc limit 15 offset 0 520μs
select * from `users` where `users`.`id` in ('2') 470μs
select * from `board_categories` where `board_categories`.`id` in ('4') 270μs
select * from `board_currencies` where `board_currencies`.`id` in ('1') 250μs
select * from `files` where `files`.`id` in ('12') 270μs
select * from `board_categories` 240μs
select * from `board_currencies`

Which is so, without with :
$adboard = Board::orderBy('created_at','desc')->paginate(15);

select count(*) as aggregate from `boards` 260μs
select * from `boards` order by `created_at` desc limit 15 offset 0 310μs
select * from `board_categories` 240μs
select * from `board_currencies` 220μs
select * from `files` where `files`.`id` = '12' limit 1 380μs
select * from `board_categories` where `board_categories`.`id` = '4' limit 1 230μs
select * from `board_currencies` where `board_currencies`.`id` = '1' limit 1 220μs
select * from `users` where `users`.`id` = '2' limit 1

Or am I misunderstanding and doing something wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Silm, 2016-03-25
@chelkaz

with loads only those records from the specified tables that are needed. That is, they are connected. You need one record from each table, so there won't be any difference in your example.
Here is an example from the docs:

// если у вас 25 книг, будет выполнено 25 дополнительных запросов
$books = App\Book::all();

foreach ($books as $book) {
    echo $book->author->name; 
}

// ...
 // будет выполнен 1 дополнительный запрос в котором будет получено 25 книг
$books = App\Book::with('author')->get();

foreach ($books as $book) {
    echo $book->author->name;
}

That is, if you need to iterate over a number of records and get related data from other tables, then with will save you from unnecessary queries.

W
WebDev, 2016-03-25
@kirill-93

in with you list related models. Do you have these methods ('user', 'category', 'currency', 'getPhoto') described in the Board model? Judging by the requests, I don't see them there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question