英文:
Automatically delete files when a record is updated in table
问题
我有一张表,其中有字段 attachment_id
和 file_path
,file_path
字段存储与附件ID对应的S3存储桶中的路径。
在 file_path
字段的数据被更新或删除时,是否有一种方式可以从模型直接初始化一个方法或调用一个事件来删除S3中的文件?
英文:
i have a table which has the fields attachment_id
and file_path
,file_path field stores the path from s3 bucket corresponding to the attachment id .
is there any way to initialize a method or call an event directly from the model to delete file from s3 when the data in file_path
field is updated or deleted ?
答案1
得分: 1
只需在模型内或外创建一个方法或辅助程序,用于从S3存储桶中删除文件,然后设置一个观察者,在更新或删除时触发它
例如:
在您的模型中:
class WhatEver extends Model {
public function deleteS3File($path) {
// 在这里编写删除代码
}
}
然后生成一个观察者:
php artisan make:observer WhatEverObserver --model=WhatEver
然后,您可以在“updated”和“deleting”事件上调用该方法:
class WhatEverObserver {
// 当模型更新时运行
public function updated(WhatEver $whatEvah) {
// 仅在file_path列更改时触发
if ($whatEvah->isDirty('file_path')) {
// 获取先前的file_path记录
$oldPath = $whatEvah->getOriginal('file_path');
// 删除先前的file_path
$whatEvah->deleteS3File($oldPath);
}
}
// 在模型删除时删除file_path
public function deleting(WhatEver $whatEvah) {
$whatEvah->deleteS3File($whatEvah->file_path);
}
}
确保查看观察者文档
英文:
Just create a method or helper inside or outside of that model which delete the file from S3 Bucket, then setup an observer to trigger it during updated or deleting
e.i.
On your model
class WhatEver extends Model {
public function deleteS3File( $path ) {
// Delete code here
}
}
Then generate an Observer
php artisan make:observer WhatEverObserver --model=WhatEver
then you can call that method on updated
and deleting
event
class WhatEverObserver {
// Runs when model is updated
public function updated(WhatEver $whatEvah) {
// Only trigger is file_path column is changed
if ( $whatEvah->isDirty('file_path') ) {
//Get the previous file_path record
$oldPath = $whatEvah->getOriginal('file_path');
//delete the previous file_path
$whatEvah->deleteS3File( $oldPath );
}
}
// Delete the file_path during model deletion
public function deleting( WhatEver $whatEvah ) {
$whatEvah->deleteS3File( $whatEvah->file_path );
}
}
Make sure to check out Observer docs
答案2
得分: 1
你可以使用$dispatchesEvents
。
创建一个事件,然后在你的模型中:
class ClassName extends Model
{
protected $dispatchesEvents = [
'updated' => EventName::class
];
}
查看更多信息:https://laravel.com/docs/9.x/eloquent#events
英文:
You can use $dispatchesEvents
.
Create an event and then, in your model:
class ClassName extends Model
{
protected $dispatchesEvents = [
'updated' => EventName::class
];
}
Check this out for more information: https://laravel.com/docs/9.x/eloquent#events
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论