Reputation: 2235
I've got a problem while using Laravel Eloquent ORM: When inserting a new Eloquent Model in the database, the data is corrupted. To be concrete:
$newItem = new NotificationNewItem;
$newItem->item_id = $item->id; // item_id is the primary key (returned by getKeyName())
$newItem->save();
return NotificationNewItem::find($item->id);
This code does not return the same as
$newItem = new NotificationNewItem;
$newItem->item_id = $item->id;
$newItem->save();
return $newItem;
whereas the two items should be the same, shouldn't they ? The weird part is that the returned JSON object (I show it directly in my browser) in the first case is exactly what is inserted in the database, and in the second case the JSON Object's primary key (here item_id) is equal to 0 even if in the database the corresponding entry has a primary key equal to 3 (or different values).
Here's the laravel code if you want to see that error again : http://pastebin.com/9wcsnvSq There are two "returns" in the model function insertAndGetElement() and those return items with different primary keys (the first one in that pastebin is returning a primary key equal to 0).
Help will be much appreciated. Thanks in advance, Robin.
Upvotes: 1
Views: 881
Reputation: 2235
The solution to that problem (Primary key set to 0 after calling save()) is to precisely define the model as not auto_incrementing the primary key. To do so, just use
public $incrementing = false;
in the model declaration. Thanks to AndreasLutro on #laravel!
Upvotes: 3
Reputation: 2962
i don't know what exactly you want, but to get last insert id use this:
$newItem = new NotificationNewItem;
$newItem->item_id = $item->id;
$newItem->save();
// $newItem->id; this is lastinsertedid
return $newItem->id;
//NotificationNewItem::find($newItem->id);
Upvotes: 0