2013-10-03 18 views
2
<?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值丟失了嗎?Laravel4模型主鍵值在插入後丟失

+0

它會在數據庫中更新嗎? –

+0

是的,它沒有例外地打印0。 – brazorf

+0

保存後是否需要輸出''id''的新值? – devo

回答

2

這是因爲您的數據庫中的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

謝謝,這其實可能是原因。無論如何,我的id沒有自動增量,因爲它是一個fk,所以這不能解決:( – brazorf

+0

你是說你的ProfileDelivery表中的id列是不同表的實際外鍵?如果是這種情況,嘗試將它重命名爲'other_table_id' –

+0

是的,我有一個用戶和他的個人資料。因爲它是0-1我不想添加多餘的索引...我仍然會檢查它 – brazorf

3

不知道,如果你解決了這個對於你的情況,但在Laravel 5.1這只是發生在我身上 - 一個表的主鍵是一樣的主鍵到另一個表,因爲有一個0或1 - 它們之間有一對一的關係。

發生的事情是Eloquent將主鍵分配給插入的最後一個插入ID,但由於主鍵不是自動遞增值,因此將其分配給零。它正確存儲在數據庫中,但如果需要使用該鍵,保存後的模型無用。解決方案是重寫具有外鍵的模型的insertAndSetId函數,以防止設置主鍵屬性。當然,你不想爲做的有一個自動遞增鍵的模型這樣做,只是你手動分配主鍵的模型。如果您不需要在創建模型後立即使用該模型,也沒有必要,因爲如上所述,數據庫中包含正確的信息。

protected function insertAndSetId(Builder $query, $attributes) 
{ 
    $id = $query->insertGetId($attributes, $keyName = $this->getKeyName()); 

    // $this->setAttribute($keyName, $id); 
} 
0

對我來說,我不得不將保護$ primaryKey設置爲模型中主鍵的列名來解決問題。 (skill_id是技能模型中的列名,所以我設置了受保護的$ primaryKey ='skill_id',默認值是'id'。)