【问题标题】:Polymorphic, many-to-one relationships in LaravelLaravel 中的多态、多对一关系
【发布时间】:2021-08-27 16:07:22
【问题描述】:

我在思考如何构建它时遇到了一些麻烦,因为它似乎是我发现的所有 Laravel 文档和其他示例的“逆向”。我可能想多了。

我发现的所有示例都假设您有一个固定数据类型(例如Comment),然后可以将其附加到任意数量的不同“所有者”。就我而言,我希望有一个“所有者”,然后可以与任意数量的不同类型相关联。

考虑以下情况:

  • 我们以Entity 开头
  • Entity 可以有任意数量的Components
  • Components 可以是两种或三种不同的可能类型之一,每种类型都有自己的数据(在自己的数据库表中),但具有通用的访问器接口
  • 给定的Entity 可能有 0 个组件、1 个组件或 24 个组件

我们希望能够检索Entity,枚举其Components,并访问它们。

我认为我有正确的数据库架构,但不知道如何制作这些类。

        Schema::create('entities', function (Blueprint $table) {
            $table->id();

            /* ... other boring stuff */

            $table->timestamps();
        });

       Schema::create('components_entities', function (Blueprint $table) {
            $table->id();

            $table->foreignIdFor(Entity::class);
            $table->string('component_type');
            $table->foreignId('component_id');

            $table->timestamps();
        });

        /* Example of type of component - class App\Models\Components\HaaProperties */
        Schema::create('ecd_propbag', function (Blueprint $table) {
            $table->id();
            $table->json('bag');
            $table->timestamps();
        });

        /* Example of type of component - class App\Models\Components\IsRecoverable */
        Schema::create('ecd_recoverable', function (Blueprint $table) {
            $table->id();
            $table->integer('recovery_time');
            $table->integer('recovery_cost');

            $table->timestamps();
        });

鉴于这种结构,我如何在类级别设置关系?

【问题讨论】:

  • 我认为您需要使用 laravel.com/docs/8.x/… 。您还打算为这些组件中的每一个制作表格吗?这听起来非常麻烦和限制。
  • @Flame 这是一个权衡...一个巨大的表(可能有 10m 行)与将其拆分,其中“所有内容”的负载要么需要许多连接,要么需要许多单独的查询。我们将看到它如何优化查询...
  • 是的 10m 很多,但如果有适当的索引,也不会太多。这完全取决于您要使用它执行哪些特定查询。将您的组件分成多个表而不是带有component_type 列的单个表,如果您只是索引该type 列,在逻辑上不应该有所作为。但是,如果您的组件需要大不相同的列,那么该单个表可能包含大量 NULL 值。

标签: laravel eloquent polymorphism


【解决方案1】:

据我了解,一个实体可以有很多组件,而组件有多种类型

//Component Model
public function type()
{
    return $this->hasOne('App\Models\Components\Type');
}
public function entity()
{
    return $this->belongsTo('App\Models\Components\Entity');
}



//Entity Model
public function components()
{
    return $this->hasMany('App\Models\Components');
}

检索实体的组件

Entity::all()->first()->components()

【讨论】:

    猜你喜欢
    • 2016-01-26
    • 1970-01-01
    • 1970-01-01
    • 2017-02-28
    • 1970-01-01
    • 2018-06-15
    • 2017-12-24
    • 2018-03-16
    • 2015-09-14
    相关资源
    最近更新 更多