mysql - Laravel Eloquent 没有将属性保存到数据库(可能是 mysql)

标签 mysql laravel save observers

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

我为我的用户模型创建了一个模型观察者。模型观察器正在“保存”时运行。当我将对象转储到要显示的用户模型的末尾时(这是在保存之前......根据 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 的问题。

最佳答案

因为我在打电话

User::create();

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

creating();

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

关于mysql - Laravel Eloquent 没有将属性保存到数据库(可能是 mysql),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27599035/

相关文章:

mysql - 查询用户聊天中未读消息

php - Laravel Eloquent 关系不起作用

javascript - 是否可以将 JavaScript 生成的图像保存在服务器端?

java - 是否可以将数据库文件保存到SD卡?

Laravel 响应函数只返回 200?

php - 在 php 中创建嵌套组时打破循环

mysql - 找不到 DBI.pm,即使它在路径中

mysql - 使用同一个表中的数据更新表

python - 如何在保存之前更改 Django 表单字段值?

使用 [charlist] 通配符的 mysql 语句