【问题标题】:Laravel Eloquent is not saving properties to database ( possibly mysql )Laravel Eloquent 没有将属性保存到数据库(可能是 mysql)
【发布时间】:2014-12-22 08:29:01
【问题描述】:

我遇到了一个奇怪的问题。

我为我的用户模型创建了一个模型观察者。模型观察者正在“保存”运行。当我在要显示的用户模型的最后转储对象时(这是在它保存之前..根据 laravel 文档)它显示为对象正确设置的所有属性,我什至看到了一个错误显示正确的属性设置并插入到我的数据库表中。但是,在保存完成并查询数据库后,其中两个字段没有保存到表中。

在我转储属性以检查它们是否已设置和保存到数据库的操作之间,我没有编写任何代码。所以我不知道是什么导致了这种情况发生。所有名称都设置正确,就像我说的那样,属性显示为被插入到数据库中,它们永远不会被保存,我没有收到错误消息,并且十个属性中只有两个没有被保存。

在我的搜索中,我发现许多帖子详细说明了应该设置 $fillable 属性,或者与变量被错误命名或未设置的问题相关的问题,但是因为我已经在 $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 的问题。

【问题讨论】:

  • 您需要显示填充用户对象并保存项目的代码

标签: mysql laravel save observers


【解决方案1】:

因为我打电话

User::create();

我想我会尝试让我的观察者听:

creating();

我不确定为什么它只影响日期和城市变量,但是将函数更改为在创建()而不是保存()时进行侦听似乎解决了我的问题。

【讨论】:

    猜你喜欢
    • 2014-11-04
    • 1970-01-01
    • 1970-01-01
    • 2017-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-30
    • 1970-01-01
    相关资源
    最近更新 更多