php - Laravel deleting polymorph relations having possibly wrong relations -
i have model represents report user. report model has polymorphic relationship can contain either recipe or comment.
the goal able delete comment or user , have related reports removed eloquent.
with current setup (seen below) not work, when deleting comment report remains , causes error since points non-existing comment.
what doing wrong? need "belongsto" relationship on polymorphic model? if how build relationship when relation morphable?
models
polymorphic model
class report extends model { public function reportable() { return $this->morphto(); } public function user() { return $this->belongsto('app\user'); } }
recipe model
class recipe extends model { public function user() { return $this->belongsto('app\user'); } public function reports() { return $this->morphmany('app\report', 'reportable'); } }
comment model
class recipecomment extends model { public function user() { return $this->belongsto('app\user'); } public function reports() { return $this->morphmany('app\report', 'reportable'); } }
laravel doesn't have built in automatically delete related records. need build functionality yourself, can done using model events. typically, setup deleting
event takes care of deleting related records inside transaction.
a laravel 5 model observer this:
class recipecommentobserver { public function deleting($model) { try { db::transaction(function() use ($model) { /** * try delete necessary related objects when object deleted. */ // detach many-manys model, delete // records in pivot table. // e.g. if had many-many relationship named 'tags': // $model->tags()->detach(); // one-one , one-many relations try , delete // example, want 'reports' here. // don't delete user when deleting comment. $relations = ['reports']; foreach ($relations $relation) { // list of related ids relation $ids = $model->$relation()->lists('id'); // use ->destroy method events fired deleted objects // if amount deleted less expected, error occurred if (!empty($ids) && $model->$relation()->getrelated()->destroy($ids) < count($ids)) { throw new exception('error occurred deleting ' . $relation); } } }); } catch (exception $e) { throw $e; } } }
with class setup, register observer in boot()
method in app/providers/eventserviceprovider.php
:
public function boot(dispatchercontract $events) { parent::boot($events); recipecomment::observe(new recipecommentobserver()); }
Comments
Post a Comment