Laravel4型号主键值插入后丢失 [英] Laravel4 Model primary key value is lost after insert
本文介绍了Laravel4型号主键值插入后丢失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
<?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值丢失?
Can anyone explain me why the ID value is lost?
推荐答案
这是因为您的数据库中的id列可能没有自动增量设置。
This is because your id column in the database probably does not have autoincrement set.
我尝试了一个没有自动增量的测试模型,它返回0,但是当我将id列更改为自动增量时,它正确地返回了该id。
I tried this with a test model without autoincrement and it returns 0, but when I changed the id column to autoincrement it returned the id correctly.
检查此功能在laravel /框架/ Src /照明/数据库/口述/ Model.php
Check this function in laravel/Framework/Src/Illuminate/Database/Eloquent/Model.php
它表示将插入并设置id,如果它具有自动增量。
It says it will insert and set id if it has autoincrement.
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;
}
这篇关于Laravel4型号主键值插入后丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文