2014-03-06 23 views
1

我在使用Laravel Eloquent ORM时遇到问题: 在数据库中插入新的Eloquent模型时,数据已损坏。 要具体:Laravel 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(),并用不同的主键的回报项目(即引擎收录的第一个返回一个主键等于0)。

帮助将不胜感激。 在此先感谢, 罗宾。

回答

3

的解决这一问题(主键设置为0后调用保存())是精确将模型定义为不auto_incrementing主键。 要做到这一点,只需使用

public $incrementing = false; 

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

0

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

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

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

相关问题