【发布时间】: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