Sve*_*rov 4 php laravel eloquent
我想将产品添加到数据库中,如果没有使用相同的产品product_name,brand,weight和volume.
这是我的代码:
$product = Product::firstorNew(['product_name'=>$request->product)], ['brand'=>$reques->brand), ['weight'=>$request->weight], ['volume'=>$request->volume]);
$product->product_name = $request->product;
$product->brand = $request->brand;
$product->weight = $request->weight;
$product->volume = $request->volume;
$product->save();
Run Code Online (Sandbox Code Playgroud)
此代码不检查所有属性,只检查第一个属性,如果匹配,则更新行而不是添加新属性.例如,在数据库中有一个产品id=1,product_name='Milk',brand='Parmalat',weight='null',volume=1如果我加入product_name='Milk',brand='Unimilk',weight='null',volume=0.5一行ID = 1将被更新,但在这种情况下,我想一个新行添加到数据库.
小智 8
看起来您的括号放错了.试试这个:
$product = Product::firstOrNew([
'product_name' => $request->product,
'brand' => $request->brand,
'weight' => $reqeust->weight,
'volume' => $request->volume,
]);
Run Code Online (Sandbox Code Playgroud)