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

$user->delete();

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

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

最好是在模型类内部。


当前回答

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

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

其他回答

我相信这是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..

我在《Laravel 8》中使用了这种方法:

public static function boot() {

    parent::boot();
    
    static::deleted(function($item){
        $item->deleted_by = \Auth::id(); // to know who delete item, you can delete this row
        $item->save();  // to know who delete item, you can delete this row
        foreach ($item->photos as $photo){
            $photo->delete();
        }
    });
}

public function photos()
{
    return $this->hasMany('App\Models\Photos');
}

注意:在此语法中删除$user->photos()->delete();对我没用……

我将遍历集合,在删除对象本身之前分离所有内容。

这里有一个例子:

try {
        $user = User::findOrFail($id);
        if ($user->has('photos')) {
            foreach ($user->photos as $photo) {

                $user->photos()->detach($photo);
            }
        }
        $user->delete();
        return 'User deleted';
    } catch (Exception $e) {
        dd($e);
    }

我知道这不是自动的,但很简单。

另一种简单的方法是为模型提供一个方法。是这样的:

public function detach(){
       try {
            
            if ($this->has('photos')) {
                foreach ($this->photos as $photo) {
    
                    $this->photos()->detach($photo);
                }
            }
           
        } catch (Exception $e) {
            dd($e);
        }
}

然后你可以简单地在你需要的地方调用它:

$user->detach();
$user->delete();

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

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

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

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

是的,但是正如@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模型甚至没有加载)