我正在嘗試利用 Laravel 的多型關系
我正在構建一個應用程式,其中有 3 個表:products,expenses和hunts.
每個產品、費用或狩獵都屬于一個類別。我曾經有過3個不同的表product_categories,expenses_categories和hunts_categories但我不喜歡做這種方式,所以我做了一點點研究,發現這個Polimorphic關系的事情,但我真的不知道如何使用它。
我創建了一個category包含以下列的新表
$table->id();
$table->string('name');
$table->integer('categorizable_id');
$table->string('categorizable_type');
$table->foreignId('icon_id')->constrained();
我的模型看起來像
class Product extends Model
{
public function category () {
return $this->morphOne(Category::class, 'categorizable');
}
}
class Expense extends Model
{
public function category () {
return $this->morphOne(Category::class, 'categorizable');
}
}
class Hunt extends Model
{
public function category () {
return $this->morphOne(Category::class, 'categorizable');
}
}
class Category extends Model
{
public function icon () {
return $this->belongsTo(Icon::class);
}
public function categorizable () {
return $this->morphTo();
}
}
我只需要expenses表的5 個類別,因此我將它們直接播種到資料庫中,但產品類別和狩獵類別由用戶創建
在我的CategorySeeder.php檔案中,我有以下功能
public function run()
{
DB::table('categories')->insert([
['name' => 'Advertising', 'icon_id' => 1, 'categorizable_id' => ?, 'categorizable_type' => 'App\Models\Expense'],
['name' => 'Utilities', 'icon_id' => 2],
['name' => 'Shopping', 'icon_id' => 3],
['name' => 'Payroll', 'icon_id' => 4],
['name' => 'Other', 'icon_id' => 5]
]);
}
因為在創建任何費用之前我想要這些類別。我應該如何處理categorizable_id列?
uj5u.com熱心網友回復:
您不需要為此使用多型關系。您可以簡單地擁有一個類別表:
$table->id();
$table->string('name');
$table->foreignId('icon_id')->constrained();
然后有一個category_id列上你的product,expenses和hunts表:
$table->foreignId('category_id')->constrained();
您的每一個的Product,Expense以及Hunt模型將會有一個category方法:
public function category()
{
return $this->belongsTo(Category::class);
}
然后你的Category模型可能有這樣的東西:
public function products()
{
return $this->hasMany(Product::class);
}
public function expenses()
{
return $this->hasMany(Expense::class);
}
public function hunts()
{
return $this->hasMany(Hunt::class);
}
Note例如,如果您有一個模型,它可以屬于產品或費用,那么多型關系會很有用。在這種情況下,你將有列notable_type和notable_id你的notes表,然后用morphOne你的Product和Expense模型。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/317408.html
上一篇:未找到列:“欄位串列”中的1054列“type_id”未知
下一篇:sql查詢中的不明確欄位
