将相同的关系转移到核心

问题描述 投票:0回答:2

我有 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

laravel oop relation
2个回答
2
投票

在这种情况下,使用特征提供了一种更简单的方法。

trait BelongsToUser
{
    public function author(): BelongsTo
    {
        return $this->belongsTo(User::class, 'author_id');
    }
}
class Product extends Model
{
    use BelongsToUser;
}

0
投票

我也用 Trait 说 @Bulent

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;
© www.soinside.com 2019 - 2024. All rights reserved.