【问题标题】:Duplicate Entry when using firstOrCreate on Laravel?在 Laravel 上使用 firstOrCreate 时出现重复条目​​?
【发布时间】:2020-12-10 08:53:36
【问题描述】:

这是我的控制器

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 和价格的重复条目,但 created_at 和 updated_at 不同, ...

如何解决?当我要求 2,3 或 ect 时,.. 订单详细信息中不会有重复条目?

【问题讨论】:

  • 可能价格有小数,数据库在搜索时找不到记录,所以插入并截断它们。试试price => (int) substr($rowJubelio['amount'], 0, -5)/$rowJubelio['qty']

标签: laravel eloquent


【解决方案1】:

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

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 都缺少属性数组,因此它总是会创建一条新记录。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-28
    • 2019-01-18
    • 2021-11-24
    • 2020-06-21
    • 2018-11-28
    • 2023-03-21
    • 1970-01-01
    • 2021-03-18
    相关资源
    最近更新 更多