我有 CoreModel 從模型擴展
class CoreModel extends Model
{
我從 coreModel 擴展了所有模型
class Product extends CoreModel
大多數表都有一個author_id 列,該列屬于與用戶
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->foreignId('author_id')->constrained('users')
在我必須創建的每個模型中
public function author(): BelongsTo
{
return $this->belongsTo(User::class, 'author_id');
}
我需要這樣的東西。這種關系我需要轉移到coreModel,但如果這個模型有author_id,它應該在條件下作業protected $fillable
你建議怎么做?
我正在考慮撰寫特征。但我仍然必須在每個模型上使用這個特征
uj5u.com熱心網友回復:
在這種情況下,使用特征提供了一種更簡單的方法。
trait BelongsToUser
{
public function author(): BelongsTo
{
return $this->belongsTo(User::class, 'author_id');
}
}
class Product extends Model
{
use BelongsToUser;
}
uj5u.com熱心網友回復:
正如我所說的@Bulent ,我也使用了 Trait
trait Author
{
/**
* adding author_id
* @return void
*/
protected static function boot(): void
{
parent::boot();
static::creating(function ($query) {
$query->author_id = $query->author_id ?? auth()->id();
});
}
public function author()
{
return $this->belongsTo(User::class, 'author_id');
}
}
.
class Category extends Model
{
use Author;
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/441594.html
上一篇:如何正確捕獲另一個類的例外?
下一篇:從2個資料幀中提取公共資料
