【发布时间】:2021-05-23 21:40:46
【问题描述】:
我使用多态的一对一关系来让多种类型的产品共享一些字段,以优化数据库结构。我有一个 Product 父模型和一个 Shoe 模型。
问题是每次我存储一个产品(鞋子和产品)并且关系发生(productable_id 存储正确)时,在productable_type而不是看到App\Models\Shoe我看到App\Models\Product和我不知道它来自哪里。
以下是关系的方法:
在 Product.php 中
public function productable() {
return $this->morphTo();
}
在 Shoe.php 中
public function product() {
return $this->morphOne('App\Models\Product', 'productable');
}
产品表迁移:
$table->id();
$table->foreignId('product_model_id')->constrained('product_models');
$table->foreignId('owner_id')->nullable()->constrained('users')->onUpdate('cascade'); // fields for the model and the product's owner
$table->integer('productable_id');
$table->string('productable_type');
【问题讨论】:
标签: laravel eloquent polymorphism laravel-8