Why can't Laravel/Eloquent use JOIN for Eager Loading?

前端 未结 3 1255
醉梦人生
醉梦人生 2021-02-05 05:23
belongsTo(\'User\');
    }
}

class User extends Eloquent {

    public fun         


        
3条回答
  •  醉酒成梦
    2021-02-05 05:53

    My guess is that this allows for eager loading multiple one to many relationships. Say, for instance, we also had a dogs table:

    class User extends Eloquent {
    
        public function cats() {
            return $this->hasMany('Cat');
        }
    
        public function dogs() {
            return $this->hasMany('Dog');
        }
    }
    

    Now we want to eager load them both with the User:

    $users = User::with('cats','dogs')->get();
    

    There is no join that would work to combine these into a single query. However, doing a seperate query for each "with" element does work:

    select * from `users`
    select * from `cats` where `user`.`id` in ('1', '2', 'x')
    select * from `dogs` where `user`.`id` in ('1', '2', 'x') 
    

    So, while this methodology may produce an extra query in some simple circumstances, it provides the ability to eager load more complex data where the join method will fail.

    This is my guess as to why it is this way.

提交回复
热议问题