Framework: Eloquent returns id as 0 if saved when ID is filled, but non-incrementing

Created on 28 Jul 2013  路  6Comments  路  Source: laravel/framework

I have a model in which there's a PK of 'id', but it is not incrementing. It's also fillable, as I'm re-using its identifier from the third-party service I'm receiving it from. I was having some trouble getting the ID after saving, specifically for a relationship table that was getting '0' in its foreign reference field.

https://github.com/laravel/framework/blob/master/src/Illuminate/Database/Eloquent/Model.php#L1105 specifically says not all tables have to be incrementing, so I would have assumed there was a little bit of handling there. :)

While I do understand http://four.laravel.com/docs/eloquent#insert-update-delete suggests setting 'incrementing' to false when that's the case, I do think there's an opportunity to be slightly more robust in such a situation by not allowing '0' as an id when returned by performInsert() (which I guess would be from insertAndSetId())

Most helpful comment

Probably it's due to "incrementing" property on the model. Set $incrementing to false and it should work. Probably. :)

All 6 comments

I'm going to need to specific code pastes of your code with comments on what is happening that you think is incorrect.

Probably it's due to "incrementing" property on the model. Set $incrementing to false and it should work. Probably. :)

I experienced this gotcha tonight. Never noticed the $incrementing attribute before.

How come the model increments an id when it isn't an autoincrementing column in the DB? Here is my up migration for this table:

Schema::create('something', function(Blueprint $table)
{
    $table->integer('id')->unsigned();
    $table->string('name')->nullable();
    $table->string('slug')->nullable();

    $table->timestamps();
});

I have added
public $incrementing = false;
and this issue fixed. (laravel version is 4.1.*)

Can we do it like this::

We deined public $incrementing = false; once and it work for all our models.

Thanks for your input @bluesuiter

Was this page helpful?
0 / 5 - 0 ratings