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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料