Performance of the Eloquent of the Laravel relationship

Asked

Viewed 1,427 times

5

I realize that in the Laravel 4 Framework, when we have a relationship, rather than using a JOIN of Mysql in the source code of Eloquent, he uses a select.

For example. I have these two models.

class Usuario extends Eloquent{

   public function nivel()
   {
       return $this->belongsTo('Nivel');
   }
}

class Nivel extends Eloquent
{

}

When I make the following query:

$usuarios = Usuario::with('nivel')->get();

foreach($usuarios as $usuario) {

   echo $usuario->nivel->nome;
}

And I use the DB::getQueryLog(), instead of flaunting it:

SELECT * FROM usuarios JOIN niveis ON niveis.id = usuarios.nivel_id

He does that

SELECT * FROM usuarios
SELECT * FROM niveis WHERE id IN(5, 7, 8, 9, 10)

And that’s because I used the with('nivel'). 'Cause if I used to do that,:

$usuarios = Usuario::all();

foreach($usuarios as $usuario){

   echo $usuario->nivel->nome;
}

The return of DB::getQueryLog() would be this, if there are 3 users:

SELECT * FROM usuarios
SELECT * FROM niveis WHERE id = 1
SELECT * FROM niveis WHERE id = 1
SELECT * FROM niveis WHERE id = 3

That is, when I don’t specify the with, if I have 100 users in the result, it will make 100 selects to relate to the table levels

I really like to use the Laravel 4 due to its great productivity and organization.

But I would like to know if this "separate select" that it does could imply loss of performance.

1 answer

5


This resource you’re talking about is called Eager loading. It checks the links between the tables and decreases the number of darlings to increase the performance of your application.

At first, it is easier to analyze your problem considering the amount of darlings executed: number dropped from 1+n to only 1 or 2 darlings, in case of results for the first query. In this case it is quite likely that Eager loading has helped your application in terms of performance.

When Laravel makes two darlings instead of just making one using JOIN, I believe the reason is that he is unaware of the structure of your database. Probably the technical decision of Eloquent to make two queries is that, in the second query, he makes it using the primary key of the table which, by characteristic, is already indexed and certainly brings good results.

On the other hand, consultations with JOINs, in many cases, are often costly and in this case the developer himself should write the queries in the application, rather than rely on Eloquent for this.

  • +1. mainly by now I can understand what was this such Eager Loading!

  • 4

    I like to use the Laravel-debugbar to monitor my application’s querys. In addition to showing all executed querys you have an option from it that automatically runs the explain of query.

  • 1

    This debugbar is very good. I used in the projects Laravel with which I worked, also.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.