【问题标题】:Can same-table eager loads be combined in Laravel 4?可以在 Laravel 4 中组合同表急切负载吗?
【发布时间】:2013-07-06 02:20:56
【问题描述】:

我有一个模型,我急切地加载两个对另一个表的引用(在本例中为 posts.created_by_id == users.idposts.updated_by_id == users.id)。

class Post {
    protected $table = 'posts';

    public function scopeLatest() {
        return $query->with(['created_by', 'updated_by'])
                     ->orderBy('created_at', 'desc');
    }

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

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

class User {
    protected $table = 'users';

    public function posts() {
        return $this->hasMany('Post', 'created_by');
    }
}

这会导致类似以下查询:

SELECT * FROM tbl ORDER BY created_at DESC;
SELECT * FROM users WHERE id IN (?); (created_at)
SELECT * FROM users WHERE id IN (?); (updated_at)

这是有道理的 - 我们在 created_by 中加载所有引用的记录,然后在 updated_by 中加载 - 但是我们可以对其进行优化以组合 id 对 users 进行单个查询。

我的问题是:Eloquent 目前是否支持此功能?

【问题讨论】:

  • 我认为我们需要更多信息。 2个型号是什么? (用户和... tbl?)。作为结果,您希望看到哪些数据?
  • 我认为你们的关系不会这样运作。 belongsTo 接受额外的参数,告诉它在哪些列上链接表。如果您想一次获取所有信息,请查看使用 Eloquent 创建连接。 IE。 Post::latest()->join('user', 'users.id', '=', 'posts.updated_by');

标签: php laravel laravel-4 eloquent


【解决方案1】:

我认为这就是您可能正在寻找的:

class Post {
    protected $table = 'posts';

    public function scopeLatest($query) {
        return $query->with('createdBy', 'updatedBy')
                 ->orderBy('created_at', 'desc');
    }

    public function createdBy() {
        return $this->belongsTo('User','created_by_id');
    }

    public function updatedBy() {
        return $this->belongsTo('User','updated_by_id');
    }
}

class User {
    protected $table = 'users';

    public function postsCreated() {
        return $this->hasMany('Post', 'created_by_id');
    }

    public function postsUpdated() {
        return $this->hasMany('Post', 'updated_by_id');
    }
}

【讨论】:

    【解决方案2】:

    对我不起作用。似乎急切的负载仅适用于表的一个实例。对我来说,只有一个关系被填补了。 Eloquent 可能使用表名作为急切加载的指针。它会生成所有急切加载查询,但只会填充一个。

    因为这个问题,我不得不将数据分成不同的表(而且还没有时间深入研究 Eloquent 代码。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-26
      相关资源
      最近更新 更多