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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化