dongming4994 2015-11-23 23:42
浏览 208
已采纳

将自定义ID分配给Laravel Model时重复输入条目

So i'm populating my database from a CRM and i'm trying to use the provided id for each item as my primary key (I feel like this will make things less complicated, but if this is bad practice please let me know). The problem is that when the table already has some data and i rerun the function, i get this error:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '25930688' for key 'PRIMARY'

Correct me if I'm wrong, but i would've expected Eloquent to check the row exists before trying to insert it. I've tried save, create, firstOrNew, firstOrCreate. They all return the same error. I've searched far and wide but I'm quite new to this so I'm not sure I'm searching for the right terms.

$listing = Property::create([
        'id' => $property['@attributes']['id'],
        'house_flat_number' => $property['address']['name'],
        'street_address_1' => $property['address']['street'],
        'street_address_2' => $property['address']['town'],
        'postcode' => $property['address']['postcode']
  • 写回答

1条回答 默认 最新

  • dpsq8476 2015-11-24 07:49
    关注

    Use findOrNew + fill instead of create and you're good:

    $listing = Property::findOrNew($property['@attributes']['id'])
       ->fill([
         'id' => $property['@attributes']['id'],
         'house_flat_number' => $property['address']['name'],
         // ...
       ])->save();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度