簡體   English   中英

如何在數據庫中插入多個輸入的數組?

[英]How can insert array of multiple inputs in database?

我正在插入多個輸入的數組。 但是當我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());
}

您需要使用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

而不是$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],            
    ]
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM