[英]Laravel Polymorphic HasOne ,two different categories model to the same item
我正在嘗試將兩個不同的類別 model 用於相同的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
表
我看到了一些多態關系,但它是關於兩個不同的模型如何屬於一個類別,而不是關於 model 如何屬於兩個不同的類別模型
謝謝。
可以這樣做,首先您的架構看起來不錯,但您想將 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 命名空間中
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.