【问题标题】:Laravel Eager Loading, multiple same hasOne relationsLaravel Eager Loading,多个相同的hasOne关系
【发布时间】:2019-03-12 11:50:49
【问题描述】:

我有 2 个简单的模型。第一个称为 Builds,第二个称为 SlotOptions。每个构建可以有大约 5 个分配的插槽。

class BuildDB extends Model

并且有5个这样的关系slot1-5 and id changes to slot1-5_id

 public function slot1()
    {
        return $this->hasOne('\App\SlotOptions', 'id', 'slot1_id');
    }

在控制器中我这样称呼它;

BuildDB::with([ 'slot1', 'slot2', 'slot3', 'slot4', 'slot5'])->find(5);

\App\SlotOptions 模型不包含任何额外的编码。

这会生成 5 个“相同”查询。 - 如果我得到一个构建列表并且每个插槽都有 whereIn 子句,atm 急切加载将起作用,是否可以让它有一个大的wherein 子句,或者是否需要更改数据库架构。

【问题讨论】:

    标签: php laravel-5 eloquent


    【解决方案1】:

    在这种情况下无法优化预加载。

    我建议您将数据库架构更改为 many-to-many relationship
    这种设计更加灵活,可以让您在未来轻松添加更多插槽。

    使用以下列创建一个名为 build_slot_option 的数据透视表:build_idslot_option_id
    如果您想对插槽进行编号/排序,请添加额外的列。

    然后定义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);
    

    【讨论】:

    • 您应该提到您正在使用 MongoDB。这个答案真的只适用于 SQL 数据库。
    • 请创建一个新问题。
    • 当然,如果你想帮助stackoverflow.com/questions/55148861/…,我会赞成并接受,因为它只是部分工作,在 SQL 数据库中。
    猜你喜欢
    • 2021-10-17
    • 1970-01-01
    • 2020-05-23
    • 2017-06-28
    • 1970-01-01
    • 1970-01-01
    • 2016-05-29
    • 2017-05-23
    • 1970-01-01
    相关资源
    最近更新 更多