我正在尝试将一组具有相同名称的字段中的表单值存储到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
我希望如何将其存储在数据库列中
[{
"title": "First Title",
"price": "10",
"link": "https://google.com"
}, {
"title": "Second Title",
"price": "40",
"link": "https://stackoverflow.com"
}]
答案 0 :(得分:0)
要在迁移中存储JSON字段,您必须执行以下操作:
$table->json('field')
然后,如果要获取这些值,则必须将此值从JSON强制转换为Array。您可以使用$ casts属性来做到这一点。
class YourModel extends Model
{
protected $casts = [
'field' => 'array'
];
}