mardi 6 juin 2017

Eloquent Eager Loading Query - IN vs WHERE

I've turned on the Query Log from Eloquent and was quite surprised what the ORM was doing in the background, especially in Eager Loading.

Let me explain:

class User extends Model{

    protected $primaryKey = 'id_user';

    public function child(){

        return $this->hasOne('Models\Child','id_user');
    }
}

Then somewhere I'm using it like this:

User::with('child')->find(1);

The query in the Background should've been an simple WHERE using the EQUAL ( = ) operator, because the Relationship is hasOne.

But looking up at the Query Logger this operation above returns:
( Forget about the User's Query, that one is "right" )

{
    "query": "select * from `childs` where `childs`.`id_user` in (?)",
    "bindings": [
        106
    ],
    "time": 0.36
}

The Query builded by the Eloquent is using the operator IN instead of EQUAL ( = ) and this does not make sense at all unless they are equal in MySQL.

My question is: Can this Query be optimized ? Or is this query slower than using with EQUAL ( = ) ?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire