Laravel Polymorphic HasOne ,two different categories model to the same item

555 Views Asked by At

I'm trying to use two different Category model to the same items table.

I'v got 3 models

SystemCategory

Schema::create('system_categories', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->timestamps();
    });

UserCategory

Schema::create('user_categories', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->integer('user_id');
        $table->timestamps();
    });

Item

Schema::create('items', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->integer('categoryable_id');
        $table->string('categoryable_type');
        $table->timestamps();
    });

Item category could be either from system_categories or user_categories table

I saw some Polymorphic relations but its about how two different models can belongs to one category, not about how model can belongs to two different category models

Thanks.

1

There are 1 best solutions below

4
On BEST ANSWER

It can be done, first thing your schema looks ok but you want to set catagoryable_id to a bigInteger to match the id columns of the 2 category tables.

Then you would set your models up

class Item extends Model
{
    public function categoryable() 
    {
        return $this->morphTo();
    }
}

class SystemCategory extends Model
{
    public function items()
    {
        return $this->morphMany('App\Item', 'categoryable');
    }
}

class UserCategory extends Model
{
    public function items()
    {
        return $this->morphMany('App\Item', 'categoryable');
    }
}

Obviously this is presuming your models are in the App namespace