问题
This is my Controller
foreach ($dataOrder['items'] as $rowJubelio) {
DataOrderDetailEcommerce::firstOrCreate([
'order_id' => DataOrderEcommerce::firstOrCreate([
'orderid'=> $invoice,
'cust_name'=> ucwords($cust_name),
'province'=> $province,
'city'=> $city,
'district'=> $area,
'zipcode'=> $zipcode,
'phone'=>$phone,
'fleet_id'=> $fleet,
'ecommerce_id'=> $ecommerce,
'date_add'=>date('Y-m-d'),
'no_resi'=> $no_resi,
'email'=> $email,
'order_time'=> $transactionDate
])->orderid,
'sku_id'=> $rowJubelio['item_code'],
'qty'=> substr($rowJubelio['qty'], 0, -5),
'price'=> substr($rowJubelio['amount'], 0, -5)/$rowJubelio['qty']
]);
}
when first that i Called controller everything is good with cerated_at and updated_at same, when i called the controller for 2,3,4 times I get duplicate entry with the same order_id, sku_id and price, but diffrent in created_at and updated_at,...
how to solve that ? when i called for the 2,3 or ect,.. there will not have duplicate entry in order detail ?
回答1:
firstOrCreate has two parameters 1: attributes against which to check 2: values with which the record should be created
firstOrCreate(array $attributes, array $values);
When attributes are provided say like
firstOrCreate(
//attributes against which check will be made
//Eloquent will search the database to find a record with id=$idValue & name=$nameValue
// If a record is found it will be returned
['id' => $idValue, 'name' => $nameValue],
//If a record matching the above attributes is not found
//A new record with the below values array will be created in database
['name' => $nameValue, 'age' => $ageValue]
);
In your code above the attributes array is missing from both firstOrCreate so it always creates a new record.
来源:https://stackoverflow.com/questions/65231289/duplicate-entry-when-using-firstorcreate-on-laravel