问题
I'm using L5.3.31 and have the following models:
Addon
Image
Relationship:
// Addon.php
public function images()
{
return $this->hasMany('App\Image');
}
// Image.php
public function addon()
{
return $this->belongsTo('App\Addon');
}
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?
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();
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.
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.
回答1:
There is a difference between
$addon->images()->where('id', '=', $id)->delete();
and
$addon->images()->find(11)->delete();
The first one is on query builder level (this does not trigger the deleting/deleted events on the model).
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
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
来源:https://stackoverflow.com/questions/43592437/laravel-5-extend-delete-on-model