php - 为什么 Laravel/Eloquent 不能使用 JOIN 进行预加载?

标签 php join laravel-4 eloquent eager-loading

<?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 列的人,可以通过别名轻松避免:

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

更新

有人指出 Eloquent 不知道模型中表的列,但我想他们可以提供一种在模型中定义它们的方法,这样它就可以使用别名并进行适当的连接而不是额外的查询。

最佳答案

我的猜测是,这允许预先加载多个一对多关系。比如说,我们还有一张狗 table :

class User extends Eloquent {

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

    public function dogs() {
        return $this->hasMany('Dog');
    }
}

现在我们想用 User 预先加载它们:

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

没有可以将这些组合成单个查询的连接。但是,对每个“with”元素进行单独查询确实有效:

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

因此,虽然这种方法在某些简单的情况下可能会产生额外的查询,但它提供了在连接方法将失败的情况下预加载更复杂数据的能力。

这是我对为什么会这样的猜测。

关于php - 为什么 Laravel/Eloquent 不能使用 JOIN 进行预加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23920540/

相关文章:

使用连接的 mySQL 查询

php - 如何在 IIS 7.5 上设置 Laravel 项目?

mysql - 连接 3 个表所需的线索

php - Mysql 查询从 php 更新

php - 我应该如何处理预期的错误?例如。 "username already exists"

php - 清除数组中的重复项

php - 每个类别的帖子限制 10 条记录

php - Laravel Auth - 使用 md5 而不是集成的 Hash::make()

laravel - 加载带有 .html 扩展名的 laravel View

PHP 和 MySQL 错误 : mysqli_connect() [function. mysqli-connect]: (HY000/2005): 未知的 MySQL 服务器主机