繁体   English   中英

将多个数组值存储为 Laravel 中的 JSON 列

[英]Storing multiple array values as a JSON column in Laravel

我正在尝试将一组具有相同名称的字段中的表单值存储到JSON列类型中。


<?php
//Form values as an array
$title = request('title');
$price = request('price');
$link = request('link');

 $arrM = array();

 for($i = 0; $i < count($title); $i++) {
    $arrM[] = array(
       'title' => $title[$I], 
       'price' => $price[$I],
       'link' => $link[$i],    
    );
 }

 Tag::create([
  'title' => request('title'),
  'tag_points' => $arrM,
 ]);

我已经将每个值组合成一个数组并将演员表设置为一个array Laravel 将不接受以下格式

$arrM - 输出

array:2 [▼
  0 => array:3 [▼
    "title" => "First Title"
    "price" => "10"
    "link" => "https://google.com"
  ]
  1 => array:3 [▼
    "title" => "Second Title"
    "price" => "40"
    "link" => "https://stackoverflow.com"
  ]
]

错误

Argument 1 passed to Illuminate\\Database\\Grammar::parameterize() must be of the type array, string given

我希望它如何存储在 DB 列中

[{
    "title": "First Title",
    "price": "10",
    "link": "https://google.com"
}, {
    "title": "Second Title",
    "price": "40",
    "link": "https://stackoverflow.com"
}]

要存储 JSON 字段,在您的迁移中,您必须执行以下操作:

$table->json('field')

然后,如果要获取这些值,则必须将此值从 JSON 转换为 Array。 您可以通过使用 $casts 属性来做到这一点。

class YourModel extends Model
{
    protected $casts = [
        'field' => 'array'
    ];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM