简体   繁体   中英

How to delete the “event” data with “eventable” polymorphic relation

I have tables "events", "eventables" and "items".

I created a polymorphic relationship to be able to add events to all of my models. It works properly. But I have a problem with deletion.

When I create an element in "item", I also create an "Event".

 $item = new Item();
 $item->name = $request->name();
 $item->save();

 $event = Event::create(['name' => $request->name]);

 $item->attachEvents($event);

I wish I could remove this "event" from my destroy method. All I can do is detach the relationship.

public function destroy($id) {
  $item = HealthItem::findOrFail($id);
  $item->detachEvents(); // Function from custom trait, simply $this->events()->detach($events)
  $item->delete();
}

I would like that to delete the linked "Event". How can I do?

I think your problem could be on this line of code

$item->detachEvents();

would be good to have a look on that part of the code.

anyways:

  1. when you are calling detachEvents() you are calling this as a object method, if the model uses that trait thats fine

  2. You are calling detachEvents on an object of type Item, hopefully on your trait you are referencing the event that is created from that item eg instead of

$this->events()->detach($events)

the variable $events should be of type event and not Item.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM