Reputation: 41
hi I'm trying to use many to many polymorphic but somehow it doesnt work I attach my code can you find out what I do wrong?
my migration :
Schema::create('stickers', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('type');
$table->timestamps();
});
Schema::create('stickables', function (Blueprint $table) {
$table->integer('sticker_id')->nullable();
$table->integer('stickable_id');
$table->string('stickable_type');
$table->primary(['sticker_id', 'stickable_id', 'stickable_type']);
$table->foreign('sticker_id')
->references('id')->on('stickers')
->onDelete('cascade');
$table->timestamps();
});
and my models
Trip model:
public function stickables()
{
return $this->morphToMany(Stickable::class, 'stickable');
}
Stickable model:
public function trips()
{
return $this->morphedByMany(Trip::class, 'stickable');
}
controller:
public function store(Request $request)
{
$trip = new Trip();
$trip->name = $request->name;
$trip->desc = $request->desc;
$trip->creator_id = Auth::user()->id;
$trip->save();
$tags=$request->tags;
$trip->stickables()->attach($tags);
$trip->save();
return redirect('/trip');
}
Upvotes: 1
Views: 1122
Reputation: 1060
Here is how you should define your relationship:
Trip
Model:
public function stickers()
{
return $this->morphToMany(Sticker::class, 'stickable');
}
Sticker
Model:
public function trips()
{
return $this->morphedByMany(Trip::class, 'stickable');
}
You don't need a model for your relationship (Stickable
).You should create a model for stickers and define your relationship on that.
Stickable
can refer to Trip
or any other type of model you need to create a relationship with stickers. However in your code you have a stickable
method on the Trip
model, which does not make sense.
Eloquent Many to Many Polymorphic Relationships
Upvotes: 2