我要插入多个输入的数组。但是当我dd或创建它时,它不会插入或返回任何值。在这种情况下如何使用create?我是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());
}
答案 0 :(得分:0)
您需要使用save()
方法保存模型。
设置所有属性后添加:
$attribute->save();
return $attribute->id // Will be set as the object has been inserted
您还可以使用create()
方法一次创建并插入模型:
$attribute = ProductsAttribute::create([
'product_id' => $product->id,
'sku' => $val,
'size' => $data['size'][$key],
'price' => $data['price'][$key],
'stock' => $data['stock'][$key],
]);
Laravel文档:https://laravel.com/docs/5.8/eloquent#inserting-and-updating-models
答案 1 :(得分:0)
您应该使用$attribute->create()
方法来代替$attribute->save()
。
或者通过create()
方法,您可以这样做
$flight = ProductsAttribute::create(
[
'product_id' => $product->id,
'sku' => $val,
'size' => $data['size'][$key],
'price' => $data['price'][$key],
'stock' => $data['stock'][$key],
]
);