当我使用以下语法删除一行时:

$user->delete();

是否有一种方法来附加一个类型的回调,这样它就会自动这样做:

$this->photo()->delete();

最好是在模型类内部。


当前回答

要详细说明所选的答案,如果关系也有必须删除的子关系,则必须首先检索所有子关系记录,然后调用delete()方法,以便正确地触发它们的删除事件。

您可以使用更高阶的消息轻松实现这一点。

class User extends Eloquent
{
    /**
     * The "booting" method of the model.
     *
     * @return void
     */
    public static function boot() {
        parent::boot();

        static::deleting(function($user) {
             $user->photos()->get()->each->delete();
        });
    }
}

你也可以通过只查询关系ID列来提高性能:

class User extends Eloquent
{
    /**
     * The "booting" method of the model.
     *
     * @return void
     */
    public static function boot() {
        parent::boot();

        static::deleting(function($user) {
             $user->photos()->get(['id'])->each->delete();
        });
    }
}

其他回答

最好为此重写delete方法。这样,您就可以在delete方法本身中合并DB事务。如果你使用事件方式,你将不得不覆盖你的删除方法调用与DB事务每次你调用它。

在你的用户模型中。

public function delete()
{
    \DB::beginTransaction();

     $this
        ->photo()
        ->delete()
    ;

    $result = parent::delete();

    \DB::commit();

    return $result;
}

用户模型中的关系:

public function photos()
{
    return $this->hasMany('Photo');
}

删除相关记录:

$user = User::find($id);

// delete related   
$user->photos()->delete();

$user->delete();

你可以在你的迁移中设置这个:

表- >外国(user_id) - >引用(id) - >(“用户”)——> onDelete(“级联”);

来源:http://laravel.com/docs/5.1/migrations外键约束

您还可以为“on delete”和“on .”指定所需的操作 更新约束的属性: 表- >外国美元(“user_id”) - >引用(id) - >(“用户”) - > onDelete(“级联”);

使用限制()

Laravel 7之后,有了新的foreignId()和constrained()方法来定义数据库中的关系约束。可以在这些方法上使用OnDelete()方法自动删除相关记录。

古老的风格

$table->unsignedBigInterer('user_id');

$table->foreign('user_id')
    ->references('id')
    ->on('users')
    ->onDelete('cascade');

新风格

$table->foreignId('user_id')
      ->constrained()
      ->onDelete('cascade');

我相信这是Eloquent事件(http://laravel.com/docs/eloquent#model-events)的一个完美用例。你可以使用"deleting"事件来进行清理:

class User extends Eloquent { public function photos() { return $this->has_many('Photo'); } // this is a recommended way to declare event handlers public static function boot() { parent::boot(); static::deleting(function($user) { // before delete() method call this $user->photos()->delete(); // do the rest of the cleanup... }); } } You should probably also put the whole thing inside a transaction, to ensure the referential integrity..