我有 CoreModel 从 Model 扩展
class CoreModel extends Model
{
我扩展了 coreModel 的所有模型
class Product extends CoreModel
大多数表都有一个 author_id 列属于 User
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,但如果此模型在 protected $fillable
中具有author_id,它应该可以工作
我在考虑写trait。但我仍然必须在每个模型上都这样做use这个trait
在这种情况下,使用特征提供了一种更简单的方法。
trait BelongsToUser
{
public function author(): BelongsTo
{
return $this->belongsTo(User::class, 'author_id');
}
}
class Product extends Model
{
use BelongsToUser;
}
trait Author
{
/**
* adding author_id
* @return void
*/
protected static function bootAuth(): void
{
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;