我正在尝试对同一个items
表使用两个不同的类别模型。
我有3个模型
SystemCategory
Schema::create('system_categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->timestamps();
});
UserCategory
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
表
我看到了一些多态关系,但它涉及两个不同模型如何属于一个类别,而不是模型如何属于两个不同类别模型
谢谢。
答案 0 :(得分:2)
可以做到的,首先,您的架构看起来不错,但您想将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('App\Item', 'categoryable');
}
}
class UserCategory extends Model
{
public function items()
{
return $this->morphMany('App\Item', 'categoryable');
}
}
显然,这是假设您的模型位于App名称空间中