3
<?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 值丢失了?

4

3 回答 3

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);
}
于 2015-07-10T21:47:07.270 回答
2

这是因为您在数据库中的 id 列可能没有设置自动增量。

我用没有自动增量的测试模型尝试了这个,它返回 0,但是当我将 id 列更改为自动增量时,它正确地返回了 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;
    }
于 2013-10-03T14:55:38.897 回答
0

对我来说,我必须将protect $primaryKey 设置为模型中主键的列名才能解决问题。(skill_id 是列名,所以在技能模型中我设置了 protected $primaryKey = 'skill_id',默认为 'id'。)

于 2015-08-11T19:57:00.863 回答