1

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.

Example:

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

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

Is Eloquent doing this or I doing something wrong with the Relationship ?

Igor Morse
  • 657
  • 2
  • 8
  • 20

0 Answers0