[英]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.