Laravel 将一个模型实例转换为集合

Jam*_*mie 5 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))
        {
            Storage::disk('s3')->delete($path);
            if(!Storage::disk('s3')->exists($path))
            {
                $attachment = File::find($file->id);
                $attachment->delete();
            }
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

所以这适用于collections. one但是当我传递模型实例时如何让它发挥作用?

mck*_*yin 8

您可以通过不同的方式使其成为可能。您可以检查是否$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
}
Run Code Online (Sandbox Code Playgroud)


And*_*orn 1

首先,由于您想要应用于集合元素或 Eloquent 模型的算法是相同的,因此将其移动到私有方法中,如下所示:

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后修改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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我们在这里做什么?我们正在检查 $this->files 实例是否是 Eloquent Collection,如果条件为 true,我们将使用 _removeFilesFromMessage 作为 map 方法的回调。否则(我假设 $this->files 包含一个 Eloquent Model 实例),将调用 _removeFilesFromMessage 方法并传递模型。

我认为这段代码是满足您需求的良好开端。

编辑

由于这个问题的标题与您所要求的部分不同......为了完成问题:

您可以使用collect()方法创建Laravel集合,如Laravel 5.3官方文档中所述