我正在尝试对同一个items
表使用两个不同的类别模型。
我有 3 个模型
系统类别
Schema::create('system_categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->timestamps();
});
用户类别
Schema::create('user_categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->integer('user_id');
$table->timestamps();
});
项目
Schema::create('items', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->integer('categoryable_id');
$table->string('categoryable_type');
$table->timestamps();
});
项目类别可以来自system_categories
表或user_categories
表
我看到了一些多态关系,但它是关于两个不同的模型如何属于一个类别,而不是关于模型如何属于两个不同的类别模型
谢谢。
可以做到,首先你的架构看起来不错,但你想catagoryable_id设置为 bigInteger 以匹配 2 个类别表的 id 列。
然后,您将设置模型
class Item extends Model
{
public function categoryable()
{
return $this->morphTo();
}
}
class SystemCategory extends Model
{
public function items()
{
return $this->morphMany('AppItem', 'categoryable');
}
}
class UserCategory extends Model
{
public function items()
{
return $this->morphMany('AppItem', 'categoryable');
}
}
显然,这是假设您的模型位于 App 命名空间中