laravel 如何将 2 个数组存储到数据库的同一行中
laravel how to store 2 array into same row on DB
我正在研究 laravel 5.1。我一直在思考如何将我的 2 个数组输入存储到数据库的同一行中。我只知道如何存储一个数组。
$amount[] = $request->amount;
$receipt[] = $request->receipt;
foreach ($amount as $key => $value) {
$reimbursement_item = ReimbursementItem::create([
'user_id' => $user->id,
'amount' => $value,
]);
}
DB structure and aspect result:
id user_id amount receipt
-- ------- ------ --------------
1 32 40.00 /images/r1.jpg
2 24 60.00 /images/r2.jpg
如果你能更新你的请求对象结构就更好了,就像应该有一个数组,数组的每个索引都有金额和收据的值,而不是单独的金额和收据数组
$data[] = $request->data;
foreach ($data as $key => $value) {
$reimbursement_item = ReimbursementItem::create([
'user_id' => $user->id,
'amount' => $value['amount'],
'receipt' => $value['receipt']
]);
}
另一种方法是,如果数组 $amount
和 $receipt
的长度每次都相同,并且值的顺序正确,您也可以在单循环中更新数据,例如
foreach ($amount as $key => $value) {
$reimbursement_item = ReimbursementItem::create([
'user_id' => $user->id,
'amount' => $value,
'receipt' => (isset($receipt[$key]))? $receipt[$key]: null
]);
}
我正在研究 laravel 5.1。我一直在思考如何将我的 2 个数组输入存储到数据库的同一行中。我只知道如何存储一个数组。
$amount[] = $request->amount;
$receipt[] = $request->receipt;
foreach ($amount as $key => $value) {
$reimbursement_item = ReimbursementItem::create([
'user_id' => $user->id,
'amount' => $value,
]);
}
DB structure and aspect result:
id user_id amount receipt
-- ------- ------ --------------
1 32 40.00 /images/r1.jpg
2 24 60.00 /images/r2.jpg
如果你能更新你的请求对象结构就更好了,就像应该有一个数组,数组的每个索引都有金额和收据的值,而不是单独的金额和收据数组
$data[] = $request->data;
foreach ($data as $key => $value) {
$reimbursement_item = ReimbursementItem::create([
'user_id' => $user->id,
'amount' => $value['amount'],
'receipt' => $value['receipt']
]);
}
另一种方法是,如果数组 $amount
和 $receipt
的长度每次都相同,并且值的顺序正确,您也可以在单循环中更新数据,例如
foreach ($amount as $key => $value) {
$reimbursement_item = ReimbursementItem::create([
'user_id' => $user->id,
'amount' => $value,
'receipt' => (isset($receipt[$key]))? $receipt[$key]: null
]);
}