Laravel Eloquent:模型删除时的连带删除
删除一条数据库记录的时候希望能自动删除这条记录关联的其它数据,如删除用户后连带删除其创建的文章和图片。
可以用Eloquent
的deleting
事件来实现:
class User extends Eloquent
{
public function photos()
{
return $this->hasMany('Photo');
}
public function posts()
{
return $this->hasMany('Post');
}
protected static function boot()
{
parent::boot();
static::deleting(function($user) {
$user->photos()->delete();
$user->posts()->delete();
});
}
}
MySQL 数据库 Cascade
同样也可以通过 MySQL 数据库的 Cascade 级联删除来实现。迁移文件示例:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTopicsTable extends Migration
{
public function up()
{
Schema::create('topics', function(Blueprint $table) {
$table->increments('id');
$table->string('title')->index();
$table->text('body');
$table->bigInteger('user_id')->unsigned()->index();
$table->timestamps();
// 当 user_id 对应的 users 表数据被删除时,删除词条
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
public function down()
{
Schema::drop('topics');
}
}
当对应的 User 被删除时,该用户的所有 Topic 会连带删除。
不是应该用deleted嘛?
学习了
多对多无法删除
学习了
$user 变量是怎么取值的呢?你这样是得不到值的啊
要不要用事务呢?
@fivenull 兄弟 你是怎么解决的 我这里也不能触发
@JueMeiAlg 你的关联关系定义了没
@fivenull 我这里定义了关联关系,为什么删不掉所关联的评论和图片
@yibendao 仔细看你的代码,你删除用的deleted,应该是delete
@fivenull 恩。谢谢啦,刚刚我弄好了
这样做的话,就不需要
外键
了?又学一招 赞一个
这个不应该用数据库外键来实现吗?
谢谢学习了
删不了,麻烦大神们可以帮我看看吗?

@hongxin 你的 boot 方法里是
static::deleted
,删除后就找不到 worksheet 了,也找不到相应的关联模型。原文是deleting
,在删除 worksheet 前先删掉关联模型。多级关联是无法删除的哎 :sob:
controller层如何引用?