Laravel渴望加载,多个相同具有一个关系 [英] Laravel Eager Loading, multiple same hasOne relations
问题描述
我有2个简单的模型.首先,一个叫做Builds,第二个叫做SlotOptions.每个版本都可以分配5个插槽.
I have 2 simple models. First, one is called Builds and the second one is called SlotOptions. Each build can have like 5 assigned slots.
class BuildDB extends Model
并且有5个这样的关系slot1-5 and id changes to slot1-5_id
And has 5 such relations slot1-5 and id changes to slot1-5_id
public function slot1()
{
return $this->hasOne('\App\SlotOptions', 'id', 'slot1_id');
}
在控制器中我这样称呼;
In the controller I call it such way;
BuildDB::with([ 'slot1', 'slot2', 'slot3', 'slot4', 'slot5'])->find(5);
\App\SlotOptions
模型不包含任何额外的编码.
\App\SlotOptions
model doesn't contain any extra coding.
这将生成5个相同"查询. -atm急切的加载将在我获得构建列表的情况下起作用,并且每个插槽都具有whereIn子句,是否可以将其作为一个大的wherein
子句,或者是否需要更改数据库架构.
This generates 5 "same" queries. - atm the eager loading would work if I get a list of builds and each slot would have whereIn clause, is it possible to have it a one big wherein
the clause, or does it require to change the DB schema.
推荐答案
在这种情况下,无法优化紧急加载.
It's not possible to optimize eager loading in this case.
我建议您将数据库架构更改为多对-许多关系.
这种设计更加灵活,可以让您将来轻松添加更多插槽.
I recommend that you change your database schema to a many-to-many relationship.
This design is more flexible, it allows you to easily add more slots in the future.
使用以下列创建名为build_slot_option
的数据透视表:build_id
,slot_option_id
如果要对插槽进行编号/排序,请添加一列.
Create a pivot table named build_slot_option
with these columns: build_id
, slot_option_id
Add an additional column if you want to number/order the slots.
然后定义 BelongsToMany
关系:
Then define a BelongsToMany
relationship:
class BuildDB extends Model
{
public function slots()
{
return $this->belongsToMany(
SlotOptions::class, 'build_slot_option', 'build_id', 'slot_option_id'
);
}
}
BuildDB::with('slots')->find(5);
这篇关于Laravel渴望加载,多个相同具有一个关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!