[英]How can insert array of multiple inputs in database?
I'm inserting an array of multiple inputs. 我正在插入多个输入的数组。 but when i dd it or create it doesn't insert or returning any values.
但是当我dd或创建它时,它不会插入或返回任何值。 How can i use create in this situation?
在这种情况下如何使用create? I'm new to laravel.
我是laravel的新手。
foreach ($data['sku'] as $key => $val) {
$attrCountSKU = ProductsAttribute::where('sku', $val)->count();
if ($attrCountSKU > 0) {
return back()->with('error', 'SKU already exists for this product! Please input another SKU.');
}
$attrCountSizes = ProductsAttribute::where(['product_id' => $product->id, 'size' => $data['size'][$key]])->count();
if ($attrCountSizes > 0) {
return back()->with('error', 'Size already exists for this product! Please input another Size.');
}
$attribute = new ProductsAttribute;
$attribute->product_id = $product->id;
$attribute->sku = $val;
$attribute->size = $data['size'][$key];
$attribute->price = $data['price'][$key];
$attribute->stock = $data['stock'][$key];
dd($attribute);
dd($attribute->create());
}
You need to save the model, using the save()
method. 您需要使用
save()
方法保存模型。
Add this after setting all the attributes: 在设置所有属性后添加以下内容:
$attribute->save();
return $attribute->id // Will be set as the object has been inserted
You could also use the create()
method to create and insert the model in one go: 您还可以使用
create()
方法一次性创建并插入模型:
$attribute = ProductsAttribute::create([
'product_id' => $product->id,
'sku' => $val,
'size' => $data['size'][$key],
'price' => $data['price'][$key],
'stock' => $data['stock'][$key],
]);
Laravel Docs: https://laravel.com/docs/5.8/eloquent#inserting-and-updating-models Laravel文件: https ://laravel.com/docs/5.8/eloquent#inserting-and-updating-models
Instead of $attribute->create()
you should use $attribute->save()
method. 而不是
$attribute->create()
,应使用$attribute->save()
方法。
Or with the create()
method you can do like this 或者使用
create()
方法,您可以像这样
$flight = ProductsAttribute::create(
[
'product_id' => $product->id,
'sku' => $val,
'size' => $data['size'][$key],
'price' => $data['price'][$key],
'stock' => $data['stock'][$key],
]
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.