【发布时间】:2020-10-13 03:11:12
【问题描述】:
我在 laravel 应用程序中使用了多态关系的 3 个模型和迁移
模型
- 属性
- 属性值
- ModelHasAttribute
迁移
属性
Schema::create('attributes', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
属性值
Schema::create('attribute_values', function (Blueprint $table) {
$table->id();
$table->string('value');
$table->foreignId('attribute_id')->constrained();
$table->uuidMorphs('model');
$table->timestamps();
});
模型有属性
Schema::create('model_has_attributes', function (Blueprint $table) {
$table->id();
$table->foreignId('attribute_id')->constrained();
$table->foreignId('attribute_value_id')->constrained();
$table->uuidMorphs('model');
$table->timestamps();
});
现在这里所有的属性都将只使用 Attribute 模型创建,属性的值将使用所有其他模型创建,例如在我的例子中是 Category 模型。
Category类里面有这样的关系方法:
public function attributeValues()
{
return $this->morphMany(AttributeValue::class, 'model');
}
问题:我如何才能在 Category 模型中获取所有具有值的属性,您认为我的关系是正确的还是可以更好?
【问题讨论】:
标签: database laravel eloquent relationship laravel-7.x