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

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

class User extends Eloquent {

    public fun         


        
3条回答
  •  眼角桃花
    2021-02-05 05:58

    I think, join query approach has a fatal drawback when you want to use LIMIT and/or OFFSET.

    $users = User::with('cats')->get() - this will output the below 2 queries.

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

    and its not one single query as

    select * from users inner join cats on cats.user_id = users.id
    

    but lets say, we need to paginate this record set.

    User::with('cats')->paginate(10) - this will output the below 2 queries with limit.

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

    with a join, it will be like

    select * from users inner join cats on cats.user_id = users.id limit 10
    

    it will fetch 10 records but it does not mean 10 users, because every user can have multiple cats.

    Also another reason i think is, a relation between relational db and NOSQL db can be easily implemented with the separated query approach

    Also as previous answer, id is ambiguous, and you would have to prefix every statement with the table name which is not desired.

    On the other hand, JOIN is expensive than EXISTS and EXISTS is faster because it doesn't order RDBMS to fetch any data, just check whether relevant rows exist. EXISTS is used to return a boolean value, JOIN returns a whole other table.

    For Scalability purpose if following sharding architecture, will have to remove the JOIN's. This was practiced by pinterest during the scaling. http://highscalability.com/blog/2013/4/15/scaling-pinterest-from-0-to-10s-of-billions-of-page-views-a.html

提交回复
热议问题