【问题标题】:Laravel Eloquent last inserted object wrong propertiesLaravel Eloquent 最后插入的对象属性错误
【发布时间】:2014-04-08 15:01:37
【问题描述】:

我在使用 Laravel Eloquent ORM 时遇到了一个问题: 在数据库中插入新的 Eloquent 模型时,数据已损坏。 具体来说:

$newItem = new NotificationNewItem;
$newItem->item_id = $item->id; // item_id is the primary key (returned by getKeyName())
$newItem->save();
return NotificationNewItem::find($item->id);

此代码返回的结果与

不同
$newItem = new NotificationNewItem;
$newItem->item_id = $item->id;
$newItem->save();
return $newItem;

而这两个项目应该是相同的,不是吗? 奇怪的是,第一种情况下返回的 JSON 对象(我直接在浏览器中显示)正是插入到数据库中的内容,而在第二种情况下,JSON 对象的主键(这里 item_id)甚至等于 0如果在数据库中相应条目的主键等于 3(或不同的值)。

如果您想再次看到该错误,这里是 laravel 代码:http://pastebin.com/9wcsnvSq 模型函数 insertAndGetElement() 中有两个“返回”,它们返回具有不同主键的项目(该 pastebin 中的第一个返回的主键等于 0)。

我们将不胜感激。 提前致谢, 罗宾。

【问题讨论】:

    标签: orm insert laravel-4 eloquent


    【解决方案1】:

    我不知道你到底想要什么,但要获得最后一个插入 id,请使用:

    $newItem = new NotificationNewItem;
    $newItem->item_id = $item->id;
    $newItem->save();
    // $newItem->id; this is lastinsertedid
    return $newItem->id;
    //NotificationNewItem::find($newItem->id);
    

    【讨论】:

    • 这不是我的问题:我正在寻找返回刚刚插入的项目,但问题是它的一个属性(主键)似乎已损坏(数据不是它应该是的: return $newItem; 返回一个 item_id 等于 0 而它应该不同的项目)。是不是更清楚了?
    【解决方案2】:

    该问题的解决方案(调用 save() 后将主键设置为 0)是将模型精确定义为不自动递增主键。 为此,只需使用

    public $incrementing = false;
    

    在模型声明中。感谢#laravel 上的 AndreasLutro!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-08
      • 2021-07-18
      • 2014-01-31
      • 2016-12-19
      相关资源
      最近更新 更多