【发布时间】: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