Laravel 5:在模型上扩展delete() [英] Laravel 5: Extend delete() on model

查看:112
本文介绍了Laravel 5:在模型上扩展delete()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用L5.3.31,并具有以下模型:

I'm using L5.3.31 and have the following models:

插件

图片

关系:

// Addon.php
public function images()
{
    return $this->hasMany('App\Image');
}

// Image.php
public function addon()
{
    return $this->belongsTo('App\Addon');
}

我现在想扩展 delete()方法,用于删除删除图像对象时保存在文件系统上的某些图像。据我了解,为了做到这一点,我需要在Image模型上扩展 delete()方法。现在,在我的图像模型上,如果我尝试执行以下操作:

I now want to extend the delete() method to delete some images that are saved on the file system when deleting an image object. To my understand, in order to do this I need to extend the delete() method on the Image model. Now, on my image model, if I try to do this:

public function delete()
{
    dd('triggered');
    parent::delete();
}

我希望它会死掉并倾倒触发。但是什么也没发生,对象像以前一样被删除。这告诉我上述代码块在删除时不会执行,对吗?

I expect it to die and dump triggered. But nothing happens, object(s) gets deleted just like before. That tells me the above block of code doesn't get executed when deleting, right?

我还在Addon模型上尝试了相同的方法,获得了相同的结果。最后,我想完成的是

I also tried the same thing on the Addon model, same result. In the end, what I want to accomplish is this, when I do

$ addon-> images()-> delete() ; 我希望laravel删除代表每个图像对象的文件。另外,如果我执行 $ addon-> images()-> where('id','=',$ id)-> delete(); 我想要删除对象旁边具有给定id的图像文件。

$addon->images()->delete(); I want laravel to delete files representing each image object. In addition if I do $addon->images()->where('id', '=', $id)->delete(); I want to delete the images files for the given id alongside the object.

顺便说一句,我不知道这是否重要,但我已将关联关系设置为在层叠时删除,所以如果我这样做,请 $ addon-> where('id','=',$ id)-> delete(); 也会删除其相关的图像对象。

Btw, I don't know if this is important or not, but I have set the relationshipt to delete on cascade, so if I do $addon->where('id', '=', $id)->delete(); it also deletes its related image objects.

推荐答案

$ addon-> images()- > where('id','=',$ id)-> delete();

$ addon-> images()-> find(11)-> delete();

第一个位于查询构建器级别(这不会触发模型上的删除/删除事件)。

The first one is on query builder level (this does not trigger the deleting/deleted events on the model).

第二个一个是在模型级别上的(这确实会触发模型上的删除/删除事件)。
查看此文档以了解Laravel 5.4中的事件

The second one is on model level (this does trigger the deleting/deleted events on the model). Check this documentation on events in Laravel 5.4

https://laravel.com/docs/5.4/eloquent#events

您可以添加观察者来捕获删除事件并执行您想要什么
,并且在Laravel上打开和关闭了关于同一件事的问题
https://github.com/laravel/framework/issues/2536

You can add observer to catch the deleting event and do what you want and there is an issue opened and closed on Laravel about the same thing https://github.com/laravel/framework/issues/2536

这篇关于Laravel 5:在模型上扩展delete()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆