简体   繁体   English

Laravel渴望加载,多个相同具有一个关系

[英]Laravel Eager Loading, multiple same hasOne relations

I have 2 simple models. 我有2个简单的模型。 First, one is called Builds and the second one is called SlotOptions. 首先,一个叫做Builds,第二个叫做SlotOptions。 Each build can have like 5 assigned slots. 每个版本可以分配5个插槽。

class BuildDB extends Model

And has 5 such relations slot1-5 and id changes to slot1-5_id 并且有5个这样的关系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 model doesn't contain any extra coding. \\App\\SlotOptions模型不包含任何额外的编码。

This generates 5 "same" queries. 这将生成5个“相同”查询。 - 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. -atm急切的加载将在我获得构建列表的情况下起作用,并且每个插槽都具有whereIn子句,是否可以将wherein一个大的where子句放在wherein ,或者是否需要更改数据库架构。

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. 这种设计更加灵活,它使您将来可以轻松添加更多插槽。

Create a pivot table named build_slot_option with these columns: build_id , slot_option_id 使用以build_slot_option创建名为build_slot_option的数据透视表: build_idslot_option_id
Add an additional column if you want to number/order the slots. 如果要编号/排序插槽,请添加其他列。

Then define a BelongsToMany relationship: 然后定义一个BelongsToMany关系:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM