Laravel数组值未存储到数据库中

vfh0ocws  于 2022-11-18  发布在  其他
关注(0)|答案(1)|浏览(144)

我试图存储数组数据,但它给我空值,我不知道发生了什么。下面的响应和我的试用代码:
响应数据:

Array
(
    [0] => Array
        (
            [name] => facebook
        )

    [1] => Array
        (
            [url] => facebook
        )

    [2] => Array
        (
            [icon] => facebook
        )

    [3] => Array
        (
            [name] => linkedin
        )

    [4] => Array
        (
            [url] => linkedin
        )

    [5] => Array
        (
            [icon] => linkedin
        )

)

控制器:

for ($i = 1; $i < count($request->fields); $i++) {
            $socialitem[] = [
                'name'      =>  $request->fields['name'][$i],
                'url'       =>  $request->fields['url'][$i],
                'icon'      =>  $request->fields['icon'][$i],
                'teams_id'  =>  $team->id,
            ];
        }

        TeamsSocial_link::insert($socialitem);

我的表:

$table->bigIncrements('id');
    $table->string('name');
    $table->string('url');
    $table->string('icon')->nullable();
    $table->bigInteger('teams_id')->unsigned();

我已经尝试了上面代码来存储数组数据,但它不工作,我也研究了兴趣,并尝试这种方式,但仍然得到错误。

jmo0nnb3

jmo0nnb31#

在我看来你应该这样做

for ($i = 0; $i < count($request->fields); $i++) {
        $socialitem = [
            'name'      =>  $request->fields[$i]['name'],
            'url'       =>  $request->fields[$i]['url'],
            'icon'      =>  $request->fields[$i]['icon'],
            'teams_id'  =>  $team->id,
        ];

        TeamsSocial_link::insert($socialitem);
    }

如果只需要一个项目,则不需要循环

$socialitem = [
            'name'      =>  $request->fields[0]['name'],
            'url'       =>  $request->fields[1]['url'],
            'icon'      =>  $request->fields[2]['icon'],
            'teams_id'  =>  $team->id,
        ];

如果您希望有多个项目

for ($i = 0; $i < count($request->fields) / 3; $i = $i+3) {
        $socialitem = [
            'name'      =>  $request->fields[$i]['name'],
            'url'       =>  $request->fields[$i+1]['url'],
            'icon'      =>  $request->fields[$i+2]['icon'],
            'teams_id'  =>  $team->id,
        ];

        TeamsSocial_link::insert($socialitem);
    }

相关问题