我有一个模型,我急于将两个引用加载到另一个表(在本例中为posts.created_by_id == users.id
和posts.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
- 但我们可以对此进行优化,以便将单个查询合并到users
我的问题是:这是Eloquent目前支持的内容吗?
答案 0 :(得分:0)
对我不起作用。看起来急切负载仅适用于表的一个实例。对我来说,只有一个关系已被填补。 Eloquent可能使用表名作为急切加载的指针。它会生成所有热切的加载查询,但只会填充一个。
由于这个问题,我不得不将数据分成不同的表(并且没有时间深入挖掘Eloquent代码。)
答案 1 :(得分:0)
我认为这是你可能正在寻找的东西:
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');
}
}