【问题标题】:How do I cascade delete a polymorphic table?如何级联删除多态表?
【发布时间】:2019-10-30 07:32:46
【问题描述】:

我想要做的是,每次我删除一个 ThoughtRecord 时,我都想删除多态地属于该 ThoughtRecord 的 cmets。

ThoughtRecordController

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

【问题讨论】:

  • 你的模型设计错了。
  • 怎么回事?我的 cmets 与其他模型具有多态关系。

标签: mysql laravel eloquent laravel-6


【解决方案1】:

一个选项:

使用此包管理级联删除:

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

            });

    }

第三个选项:

当您使用多态关系时,您可能还会将其用作特征。如果是这种情况,您可以通过挂接到删除事件来删除 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();
        });
    }
}

选项四:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多