<?php
// Model
class ProfileDelivery extends \Eloquent {
protected $table = 'profile_delivery';
protected $guarded = array();
public $timestamps = FALSE;
}
// Somewhere
$deliveryGuy->id = 1;
print $deliveryGuy->id; // Prints 1
if (!$deliveryGuy->save()) {
throw new \Exception('Cant save .');
}
print $deliveryGuy->id; // Prints 0
任何人都可以解释为什么ID值会丢失吗?
答案 0 :(得分:4)
不确定你是否为你的情况解决了这个问题,但在Laravel 5.1中这恰好发生在我身上 - 一个表的主键与另一个表的主键相同,因为存在0或1对1的关系他们之间。
发生的事情是Eloquent将主键分配给插入的最后一个插入ID,但由于主键不是自动增量值,因此将其分配给零。它正确存储在数据库中,但如果需要使用该密钥,则保存后的模型无用。解决方案是覆盖具有外部主键的模型的insertAndSetId函数,以防止其设置主键属性。当然,对于做具有自动递增键的任何模型,您不希望这样做,只是您手动分配主键的模型。如果您在创建模型后不需要立即使用该模型也没有必要,因为正如我上面所述,数据库中包含正确的信息。
protected function insertAndSetId(Builder $query, $attributes)
{
$id = $query->insertGetId($attributes, $keyName = $this->getKeyName());
// $this->setAttribute($keyName, $id);
}
答案 1 :(得分:2)
这是因为数据库中的id列可能没有设置自动增量。
我尝试使用没有自动增量的测试模型并返回0,但是当我将id列更改为autoincrement时,它正确地返回了id。
在laravel / Framework / Src / Illuminate / Database / Eloquent / Model.php中检查此功能
它表示如果它有自动增量,它将插入并设置id。
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;
}
答案 2 :(得分:0)
对我来说,我必须将保护$ primaryKey设置为模型中主键的列名来解决问题。 (skill_id是列名,因此在Skill模型中我设置了protected $ primaryKey ='skill_id',默认为'id'。)