php 如何在Laravel上保存和检索数组

i34xakig  于 2022-12-02  发布在  PHP
关注(0)|答案(1)|浏览(115)

好吧,我保存一个数组到'year'列表硬币,当试图检索我不能做一个foreach每年.错误出现在刀片上,当试图foreach $coin-〉year它说它是一个int(我不明白为什么它是int而不是数组).

硬币播种机:

Coin::create([
    'name' => 'Coat of Arms of Andorra',
    'year' => array(2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022),
    'description' => 'The coat of arms of Andorra has existed for centuries. This coat of arms has been the national coat of arms of Andorra since 1969. Below the shield arms stands Andorra\'s national motto Virtus Unita Fortior (Latin for United virtue is stronger). The coat of arms also appears on the flag of Andorra.',
    'image' => 'andorra.png',
    'country_id' => 6,
    'type' => 'circulation',
]);

投币控制器:

public function catalog($id): Factory|View|Application
{
    return view("/catalog",
        ["coinImageType" => $id,
            "coins" => Coin::where('type', $id)->get(),
            "coinName" => Coin::distinct()->get('country_id', $id),
            "coinType" => Coin::distinct()->get('type')]);
}

表格image
目录刀片式服务器

@foreach($coins as $coin)
    <div><h1>$coin->name</h1>
    </div>
    <div>
        @foreach($coin->year as $year)
        {{$year}}
        endforeach
    </div>
@endforeach

我试过内爆,json编码,序列化...

6uxekuva

6uxekuva1#

您需要在将数组保存到db之前对其进行序列化。

Coin::create([
'name' => 'Coat of Arms of Andorra',
'year' => serialize(array(2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022)),
'description' => 'The coat of arms of Andorra has existed for centuries. This coat of arms has been the national coat of arms of Andorra since 1969. Below the shield arms stands Andorra\'s national motto Virtus Unita Fortior (Latin for United virtue is stronger). The coat of arms also appears on the flag of Andorra.',
'image' => 'andorra.png',
'country_id' => 6,
'type' => 'circulation',]);

当您需要在foreach中使用

unserialize($coin->year);

相关问题