Jahongir Tursunboyev
Jahongir Tursunboyev

Reputation: 366

transfer the same relation to the core

i have CoreModel extends from Model

class CoreModel extends Model
{

and I extended all the models from coreModel

class Product extends CoreModel

most tables have an author_id column that belongsTo with User

Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->foreignId('author_id')->constrained('users')

inside each model I have to create

public function author(): BelongsTo
{
    return $this->belongsTo(User::class, 'author_id');
}

I need something like that. this relationship ni I need to move to coreModel but it should work with condition if this model has author_id in protected $fillable

What do you advise to do ?

I was thinking about writing trait .but I still have to do it on every model use this trait

Upvotes: 1

Views: 73

Answers (2)

Jahongir Tursunboyev
Jahongir Tursunboyev

Reputation: 366

I also used Trait as said @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;

Upvotes: 0

Bulent
Bulent

Reputation: 3411

In such cases, using traits provides an easier way.

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

Upvotes: 2

Related Questions