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

$user->delete();

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

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

最好是在模型类内部。


当前回答

$table->foreignId('user_id')->constrained('user')->cascadeOnDelete();

or

$table->foreignId('user_id')->constrained()->cascadeOnDelete();

其他回答

在定义模型迁移时最好使用onDelete级联。它负责为你删除模型的关系:

e.g.

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

如果您碰巧发现自己正在考虑如何删除一个模型及其关系到大于3或4个嵌套关系的级别,那么您应该考虑重新定义您的模型关系。

有3种方法可以解决这个问题:

1. 在模型引导上使用雄辩事件(参考:https://laravel.com/docs/5.7/eloquent#events)

class User extends Eloquent
{
    public static function boot() {
        parent::boot();

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

2. 使用雄辩的事件观察者(参考:https://laravel.com/docs/5.7/eloquent#observers)

在你的AppServiceProvider中,像这样注册观察者:

public function boot()
{
    User::observe(UserObserver::class);
}

接下来,添加一个Observer类,如下所示:

class UserObserver
{
    public function deleting(User $user)
    {
         $user->photos()->delete();
    }
}

3.使用外键约束(参考:https://laravel.com/docs/5.7/migrations#foreign-key-constraints)

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

在我的情况下,这是相当简单的,因为我的数据库表是InnoDB与外键级联删除。

因此,在这种情况下,如果照片表包含用户的外键引用,那么您所要做的就是删除酒店,清理工作将由数据库完成,数据库将从数据库中删除所有照片记录。

要详细说明所选的答案,如果关系也有必须删除的子关系,则必须首先检索所有子关系记录,然后调用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();
        });
    }
}

是的,但是正如@supersan在上面的评论中所说,如果你在QueryBuilder上删除(),模型事件将不会被触发,因为我们没有加载模型本身,然后在该模型上调用delete()。

只有在模型实例上使用delete函数时,才会触发事件。

所以,有人说:

if user->hasMany(post)
and if post->hasMany(tags)

为了在删除用户时删除post标签,我们必须遍历$user->个帖子,并调用$post->delete()

Foreach ($user->posts as $post) {$post->delete();} ->这将在Post上触发删除事件

VS

$user->posts()->delete() ->这将不会在post上触发删除事件,因为我们实际上没有加载post模型(我们只运行SQL: delete *从user_id = $user->id的帖子,因此,post模型甚至没有加载)