首页 > 解决方案 > 如何级联删除多态表?

问题描述

我想做的是每次删除 ThoughtRecord 时,我都想删除多态地属于该 ThoughtRecord 的评论。

思想记录控制器

public function destroy(ThoughtRecord $thoughtRecord)
{
    $thoughtRecord->delete();
}

思想记录模型

public function comments()
{
    return $this->morphMany('App\Comment', 'commentable');
}

评论模型

public function commentable()
{
    return $this->morphTo();
}

思想记录表

$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();

标签: mysqllaraveleloquentlaravel-6

解决方案


一种选择:

使用此包管理级联删除:

用于管理级联删除的包

第二种选择:

你可以监听 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();

            });

    }

第三个选项:

当您使用多态关系时,您可能还会将其用作特征。如果是这种情况,您可以通过连接到删除事件来删除特征引导方法中的关系。

<?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();
        });
    }
}

选项四:

只需简单的代码,覆盖您模型上的删除方法。如果此模型被删除,请删除其他关联模型。

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


推荐阅读