Php Laravel将一个模型实例转换为集合
我正在使用Laravel 5.3,并试图从作业中的用户删除文件::Php Laravel将一个模型实例转换为集合,php,collections,laravel-5.3,Php,Collections,Laravel 5.3,我正在使用Laravel 5.3,并试图从作业中的用户删除文件:: public function handle() { //Remove all files from a message $this->files->map(function($file) { $path = $file->getPath(); if(Storage::disk('s3')->exists($path)) {
public function handle()
{
//Remove all files from a message
$this->files->map(function($file) {
$path = $file->getPath();
if(Storage::disk('s3')->exists($path))
{
Storage::disk('s3')->delete($path);
if(!Storage::disk('s3')->exists($path))
{
$attachment = File::find($file->id);
$attachment->delete();
}
}
});
}
因此,这适用于
集合
。但是,当我通过一个模型实例时,如何使其工作 你可以用不同的方式使之成为可能。您可以检查$this->filies
if($this->files instanceof Illuminate\Database\Eloquent\Collection) {
//so its a collection of files
} else {
//its a one model instance
//here you can do hack,
$this->files = collect([$this->files]);
//and code will works like a magic
}
首先,由于要应用于集合元素或雄辩模型的算法相同,请将其移动到私有方法中,如下所示:
private _removeFilesFromMessage($file) {
$path = $file->getPath();
if(Storage::disk('s3')->exists($path))
{
Storage::disk('s3')->delete($path);
if(!Storage::disk('s3')->exists($path))
{
$attachment = File::find($file->id);
$attachment->delete();
}
}
}
然后修改handle方法,如下所示:
public function handle()
{
if($this->files instanceof Illuminate\Database\Eloquent\Collection) {
//Remove all files from a message
$this->files->map($this->_removeFilesFromMessage($file));
} else {
$this->_removeFilesFromMessage($this->files);
}
}
我们在这里干什么?我们正在检查$this->files实例是否是一个有说服力的集合,如果条件为true,我们将使用_removeFilesFromMessage作为map方法的回调。否则(我假设$this->files包含一个雄辩的模型实例)调用_removeFilesFromMessage方法并传递模型
我认为这段代码是满足您需求的一个良好开端
编辑
由于这个问题的标题与你所问的部分不同。。。关于完成事项:
您可以使用collect()方法创建Laravel集合,如中所述。当然,您只需检查$this->files
如果(!($this->files instanceof light\Database\elounce\Collection)){$this->files=collect([$this->files]);}