2014-12-22 151 views
2

我遇到一個奇怪的問題。Laravel Eloquent未將屬性保存到數據庫(可能是mysql)

我爲我的用戶模型創建了一個模型觀察者。模型觀察者正在'保存'中運行。當我在要顯示的用戶模型的最後轉儲對象時(根據laravel文檔,這只是在它保存之前)它顯示爲對象正確設置的所有屬性,我甚至看到了一個顯示的錯誤正確的屬性設置並插入到我的數據庫表中。但是,完成保存並查詢數據庫後,其中兩個字段未保存到表中。

沒有我自己寫的代碼,在我傾銷屬性以檢查它們已被設置和保存操作到數據庫之間。所以我不知道可能會導致這種情況發生。所有的名字都設置正確,就像我說的那樣,屬性顯示爲插入到數據庫中,它們只是永遠不會被保存,我沒有收到錯誤消息,並且只有十分之二的屬性沒有被保存。

在我的搜索中,我發現許多帖子詳細說明應該設置$ fillable屬性,或者與變量問題有關的問題被錯誤命名或取消設置,但是因爲我已經在$中指定了未保存的特定屬性因爲他們打印的數據與預期的完全一致,所以我不認爲這些問題與我遇到的問題有關。

救我打電話:

User::create(Input::all()); 

,然後處理該數據觀察者看起來是這樣的:

class UserObserver { 

    # a common key between the city and state tables, helps to identify correct city 
    $statefp = State::where('id',$user->state_id)->pluck('statefp'); 

    # trailing zeros is a function that takes the first parameter and adds zeros to make sure 
    # that in this case for example, the dates will be two characters with a trailing zero, 
    # based on the number specified in the second parameter 
    $user->birth_date = $user->year.'-'.$user->trailingZeros($user->month, 2).'-'.$user->trailingZeros($user->day, 2); 

    if(empty($user->city)){ 
     $user->city_id = $user->defaultCity; 
    } 

    $user->city_id = City::where('statefp', $statefp)->where('name', ucfirst($user->city_id))->pluck('id'); 

    # if the user input zip code is different then suggested zip code then find location data 
    # on the input zip code input by the user from the geocodes table 
    if($user->zip !== $user->defaultZip){ 
     $latlon = Geocode::where('zip', $user->zip)->first(); 
     $user->latitude = $latlon['latitude']; 
     $user->longitude = $latlon['longitude']; 
    } 

    unset($user->day); 
    unset($user->month); 
    unset($user->year); 
    unset($user->defaultZip); 
    unset($user->defaultCity); 
} 

是對於那些不是兩個數值的代碼設置,當我運行

dd($user); 

所有的變量設置正確,並顯示在mysql插入嘗試屏幕正確的值,但他們不會堅持過去那一點..在我看來,可能mysql拒絕city_id和birth_date的值。但是,我不明白爲什麼,或者它是否與Laravel或MySQL有關。

+1

您需要顯示填充User對象並保存項目的代碼 – Varedis

回答

0

因爲我打電話

User::create(); 

我想我會盡量讓我的觀察者聽:

creating(); 

我不知道爲什麼它只是實現的日期和城市變量,但更改函數以listen()而不是save()方式似乎解決了我的問題。

相關問題