【问题标题】:working with the collection of objects in laravel在 laravel 中处理对象的集合
【发布时间】:2020-02-20 02:49:14
【问题描述】:

尝试使用对象集合。
该系列不是 Eloquent 而是手工制作的 Illuminate\Support\Collection

如果我在对象集合的情况下理解正确,我将无法使用大多数方法,而只能使用那些可以使用回调的方法。

所以,我收集了一些对象:

这里是代码($country = 'Russia'):

        dump($this->countries);
        $filtered = $this->countries->filter(function ($countryObj) use($country) {
            dump($countryObj->name == $country);
            return $countryObj->name == $country;
        });
        dd($filtered);

我希望 $filtered 只包含一个元素,即返回 true 的元素(在我们的例子中是俄罗斯) 但不是它,我有相同的 3 个元素集合。

这里是其余的类,以确保它们与集合相关

use App\Services\Taxes\DataSourceInterface;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

abstract class JsonModel extends Collection implements DataSourceInterface
{
    public function __construct()
    {
        parent::__construct($this->readDataFile(env('JSON_DATA_PATH')));
    }

    protected function readDataFile(string $path): array
    {
        $disk = Storage::disk('local');

        try {
            $dataObj = json_decode($disk->get($path), false, 10, JSON_THROW_ON_ERROR);
            return $this->loadData($dataObj);
        } catch (FileNotFoundException $e) {
            Log::error('Storage ' . $e->getMessage() . ' was not found');
        } catch (\JsonException $e) {
            Log::error('Json DataFile: ' . $e->getMessage());
        }

        return [];
    }

    abstract protected function loadData(object $dataObject): array;
}
class JsonCountries extends JsonModel
{
    public function loadData(object $dataObject): array
    {
        $data = array_filter($dataObject->countries, function ($item){
            unset($item->states);
            return true;
        });

        return $data;
    }
}

【问题讨论】:

  • 你可以在这里发布你的JsonCountries 班级吗?也许你的 JsonCountries 类没有扩展 Collection
  • @aceraven777,我已经用其他课程更新了这篇文章。这是肯定的,至少因为我可以使用$this->countries->first()dump($this->countries instanceof Collection );这样的基本方法是真的
  • 你可以试试dd($filtered->all());
  • 我试过了,它返回所有 3 个条目

标签: laravel collections


【解决方案1】:

问题出在 new static 中,它在 laravel 方法中使用,这些方法返回集合实例,实际上我不希望在我的构造函数中有数组条目。

空数组和文件读取之间的选择修复了问题

abstract class JsonModel extends Collection implements DataSourceInterface
{
    public function __construct($dataArr = [])
    {
        if(!is_array($dataArr))
           $dataArr = $this->readDataFile(env('JSON_DATA_PATH'));

        parent::__construct($dataArr);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-29
    • 1970-01-01
    • 1970-01-01
    • 2014-05-05
    • 2019-01-25
    • 1970-01-01
    • 1970-01-01
    • 2020-04-12
    相关资源
    最近更新 更多