Duplicate Entry when using firstOrCreate on Laravel?

╄→尐↘猪︶ㄣ 提交于 2021-01-29 15:08:47

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!