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. mainly by now I can understand what was this such Eager Loading!
– Wallace Maxters
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.– gmsantos
This debugbar is very good. I used in the projects Laravel with which I worked, also.
– Rodrigo Rigotti