Laravel belongsToMany with Morph
I have Package Model
and a package
can get multi services
and multi modules
.
I was going to try to make table like this.
Schema::create('package_has_items', function (Blueprint $table) { $table->id(); $table->unsignedBigInteger('package_id'); $table->string('model_type'); // App\Service, or App\Module $table->unsignedBigInteger('model_id'); $table->timestamps(); });
I am going to make relationship between Package
and Service
, Package
and Module
so that I can use attach()
, sync()
function easily.
And I am going to get services and modules from a package with $package->services
, $package->modules
.
How can I make relationship in Package Model
?
You can use morphedByMany
. In Package
model, you can set relationship as following.
public function services() { return $this->morphedByMany(Service::class, 'model', 'package_has_items', 'package_id', 'model_id'); } public function modules() { return $this->morphedByMany(Module::class, 'model', 'package_has_items', 'package_id', 'model_id'); }