這是因爲您的數據庫中的id列可能沒有自動增加設置。
我試過這個測試模型沒有自動增量,它返回0,但是當我改變ID列自動增量它正確地返回了ID。
入住此功能laravel /框架/ src目錄/照亮/數據庫/雄辯/ Model.php
它說,它會插入,並設置標識,如果有自動遞增。
protected function performInsert($query)
{
if ($this->fireModelEvent('creating') === false) return false;
// First we'll need to create a fresh query instance and touch the creation and
// update timestamps on this model, which are maintained by us for developer
// convenience. After, we will just continue saving these model instances.
if ($this->timestamps)
{
$this->updateTimestamps();
}
// If the model has an incrementing key, we can use the "insertGetId" method on
// the query builder, which will give us back the final inserted ID for this
// table from the database. Not all tables have to be incrementing though.
$attributes = $this->attributes;
if ($this->incrementing)
{
$this->insertAndSetId($query, $attributes);
}
// If the table is not incrementing we'll simply insert this attributes as they
// are, as this attributes arrays must contain an "id" column already placed
// there by the developer as the manually determined key for these models.
else
{
$query->insert($attributes);
}
// We will go ahead and set the exists property to true, so that it is set when
// the created event is fired, just in case the developer tries to update it
// during the event. This will allow them to do so and run an update here.
$this->exists = true;
$this->fireModelEvent('created', false);
return true;
}
它會在數據庫中更新嗎? –
是的,它沒有例外地打印0。 – brazorf
保存後是否需要輸出''id''的新值? – devo