mysql - 如何级联删除多态表?
问题描述
我想做的是每次删除 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();
解决方案
一种选择:
使用此包管理级联删除:
第二种选择:
你可以监听 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
推荐阅读
- scala - 如何映射扩展共同特征的对象的 Hlist?
- java - 调用 CloseableHttpAsyncClient Close 方法时发生死锁
- three.js - 如何渲染 TextGeometry?
- haskell - 是否可以像 NPM (NodeJS) 一样设计 Stack (Haskell)?
- xquery - xquery:将 where 子句放入变量中?通过变量构建 where 子句?
- c++ - 如何计算比 O(n^2) 更好的最小平均子数组?
- javascript - 如何重构由同一函数定义的导出常量的长列表更干燥
- c# - 从 MongoDb 读取整个集合的最快方法
- linux - 如果目录已经使用 shell 脚本存在,如何避免 mkdir?
- azure - Azure Functions - 返回没有输出绑定的值?这可能吗?