I realize that in Laravel 4 Framework
, when we have a relationship, instead of using JOIN
of Mysql
in the source code of Eloquent
, it 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 DB::getQueryLog()
, instead of displaying it:
SELECT * FROM usuarios JOIN niveis ON niveis.id = usuarios.nivel_id
It does this
SELECT * FROM usuarios
SELECT * FROM niveis WHERE id IN(5, 7, 8, 9, 10)
And that's because I used with('nivel')
. For if I used to do this:
$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 do not specify with
, if I have 100 users in the result, it will make 100 selects to relate to the table levels
I really like using Laravel 4
because of its great productivity and organization.
But I wonder if this "separate select" it does could lead to performance loss.