在Laravel上使用firstOrCreate时出现重复条目​​? [英] Duplicate Entry when using firstOrCreate on Laravel?

查看:37
本文介绍了在Laravel上使用firstOrCreate时出现重复条目​​?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的控制器

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']
    ]);
}

当我第一次调用控制器时,cerated_at和updated_at都一样,当我调用控制器2、3、4次时,我得到了具有相同order_id,sku_id和price的重复条目,但created_at和updated_at有所不同,...

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,...

该如何解决?当我打电话给2,3或ect ...时,不会有重复的订单明细条目?

how to solve that ? when i called for the 2,3 or ect,.. there will not have duplicate entry in order detail ?

推荐答案

firstOrCreate有两个参数1:要检查的属性2:应使用其创建记录的值

firstOrCreate has two parameters 1: attributes against which to check 2: values with which the record should be created

firstOrCreate(array $attributes, array $values);

提供属性后,请说出

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]
);

firstOrCreate中缺少属性数组上方的代码,因此它总是创建新记录.

In your code above the attributes array is missing from both firstOrCreate so it always creates a new record.

这篇关于在Laravel上使用firstOrCreate时出现重复条目​​?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆