为什么Laravel /雄辩不能使用JOIN加载? [英] Why can't Laravel/Eloquent use JOIN for Eager Loading?

查看:137
本文介绍了为什么Laravel /雄辩不能使用JOIN加载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<?php

class Cat extends Eloquent {

    public function user() {
        return $this->belongsTo('User');
    }
}

class User extends Eloquent {

    public function cats() {
        return $this->hasMany('Cat');
    }
}

现在:

$cats = Cat::with('user')->get();

执行2个查询:

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

为什么不能这样做:

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

对于那些表示表中有两个id列的人来说,这可以通过别名轻松避免:

For those saying that there are both id columns in the table, that could be easily avoided with aliases:

select 
    c.id as cats__id,
    c.name as cats__name,
    c.user_id as cats__user_id,
    b.id as users__id,
    b.name as users__name
from cats c
inner join users b on b.id = c.user_id

更新

有人指出,口才不知道模型中的列的列,但我猜他们可以提供一种方法来定义它们那么模型就可以使用别名并进行正确的连接而不是一个额外的查询。

Someone pointed out that Eloquent doens't know the columns of the tables from the models, but I guess they could provide a way to define them in the model so then it could use aliases and do a proper join instead of an extra query.

推荐答案

我的猜测是,这允许加载多个一对多的关系。例如,我们也有一张狗桌:

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();

没有可以将这些组合到单个查询中的联接。但是,对每个with元素进行单独查询都可以正常工作:

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.

这篇关于为什么Laravel /雄辩不能使用JOIN加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆