【问题标题】:Laravel convert one model instance to collectionLaravel 将一个模型实例转换为集合
【发布时间】:2017-03-11 10:11:44
【问题描述】:

我正在使用 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();
            }
        }
    });
}

所以这适用于collections。但是,当我通过 one 模型实例时,如何让它工作呢?

【问题讨论】:

    标签: php collections laravel-5.3


    【解决方案1】:

    您可以通过不同的方式实现它。你可以检查$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
    }
    

    【讨论】:

    • 当然,你可以检查$this->filesif(! ($this->files instanceof Illuminate\Database\Eloquent\Collection)) { $this->files = collect([$this->files]); }
    【解决方案2】:

    首先,由于您要应用于集合元素的算法或 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();
            }
        }
    }
    

    然后像这样修改句柄方法:

    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 实例是否是 Eloquent 集合,如果条件为真,我们使用 _removeFilesFromMessage 作为 map 方法的回调。否则(我假设 $this->files 包含一个 Eloquent Model 实例)调用 _removeFilesFromMessage 方法并传递模型。

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

    编辑

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-30
      • 1970-01-01
      • 2021-01-11
      • 2015-04-29
      • 1970-01-01
      • 1970-01-01
      • 2016-05-12
      相关资源
      最近更新 更多