我想做的是每次删除ThoughtRecord时都想删除多义属于该ThoughtRecord的注释。
ThoughtRecordController
public function destroy(ThoughtRecord $thoughtRecord)
{
$thoughtRecord->delete();
}
ThoughtRecord模型
public function comments()
{
return $this->morphMany('App\Comment', 'commentable');
}
评论模型
public function commentable()
{
return $this->morphTo();
}
ThoughtRecord表
$table->bigIncrements('id');
$table->integer('user_id');
$table->boolean('is_authorized')->default(false);
$table->string('title')->nullable();
$table->timestamps();
评论表
$table->increments('id');
$table->integer('commentable_id');
$table->string('commentable_type');
$table->integer('user_id');
$table->text('content');
$table->timestamps();
答案 0 :(得分:0)
一个选项:
使用此软件包管理级联删除:
Package for manage cascade deletes
第二个选项:
您可以收听Laravel提供的事件
protected static function boot()
{
parent::boot();
// cause a delete of a poster to cascade
// to children so they are also deleted
static::deleting(function ($poster) {
$photos->photos->delete();
$poster->comments()->delete();
});
}
第三种选择:
当您使用多态关系时,您可能还会使用它一个特质。在这种情况下,您可以通过挂接到Delete事件来删除trait的boot方法中的关系。
<?php namespace Company\Package\Traits;
/**
* This file is part of Package.
*
* @license MIT
* @package Company\Package
*/
use Illuminate\Support\Facades\Config;
trait ActionableTrait
{
/**
* Morph Many relation with Task.
*
* @return \Illuminate\Database\Eloquent\Relations\MorphMany
*/
public function actions()
{
return $this->morphMany(Config::get('crm.action'),'actionable');
}
protected static function bootActionableTrait()
{
self::deleting(function ($model) {
$model->actions()->delete();
});
}
}
选项四:
只需简单的代码,即可在模型上覆盖delete方法。如果删除此模型,请删除其他关联的模型。
public function delete()
{
$res=parent::delete();
if($res==true)
{
$relations=$this->youRelation; // here get the relation data
// delete Here
}
}
阅读https://laravel.com/docs/5.8/eloquent-relationships#querying-polymorphic-relationships