【问题标题】:Laravel eloquent mutators not work on update dataLaravel 雄辩的变异器不适用于更新数据
【发布时间】:2018-06-29 07:17:26
【问题描述】:

我的模型访问器和修改器用于数据库表字段中的哈希/重新哈希数据。例如:

public function setFullNameAttribute($value)
{
    $this->attributes['full_name'] = Helper::geted('encrypt', $value);
}

public function getFullNameAttribute($value)
{
    return Helper::geted('decrypt', $value);
}

当我将数据保存到数据库时,所有发送的数据都以散列形式保存,但更新数据未散列。我的保存/更新代码:

$profile = [
    'full_name' => "John",
    'address' => "United Kingdom"
];

$profile_save = new Profile($profile);
$exist = Personal::where('user_id', Auth::id())->count();
if($exist == 0) $user->profile()->save($profile_save);
if($exist == 1) $user->profile()->update($profile);

当我第一次将此信息保存到数据库时:

当我第二次输入到当前 URL 数据将被更新:

为什么更新信息时不以加密形式存储信息?

【问题讨论】:

  • 发布您的Helper::geted('decrypt', $value);
  • dd($profile); (更新之前)- 发布的数据在那时是否加密?
  • 我更新了我的问题。您可以查看图片的详细信息。
  • updateOrCreate() 看起来更适合您的情况。
  • updateOrCreate() 在刷新页面或进入当前测试 url 时保存重复行。 @JonasStaudenmeir

标签: php laravel eloquent laravel-5.6


【解决方案1】:

你的问题出在这一行:

$user->profile()->update($profile);

修改器和访问器在 eloquent 上工作,而不是在查询构建器上工作。您正在使用作为查询构建器功能的更新功能,因此您正在直接更新您的数据库。 使用这个:

$profile = [
    'full_name' => "John",
    'address' => "United Kingdom"
];
$profile = auth()->user()->profile;
if ($profile) {
    $profile->full_name = $profile['full_name'];
    $profile->address = $profile['address'];
    $profile->save();
} else {
    auth()->user()->profile()->create($profile);
}

【讨论】:

  • 如何在没有查询构建器的情况下更新用户配置文件?
【解决方案2】:

对于任何有同样问题的人:

省略括号也可以解决问题,因为它使用 Eloquent 而不是 Query Builder:

$user->profile->update($profile);

【讨论】:

    【解决方案3】:

    解决方案:

    $instance->fill($request->all());
    $instance->save();
    

    不工作 $instance->update($request->all());

    【讨论】:

      猜你喜欢
      • 2020-05-30
      • 2020-02-14
      • 2023-02-02
      • 2017-04-28
      • 1970-01-01
      • 1970-01-01
      • 2020-02-08
      • 2020-12-12
      • 1970-01-01
      相关资源
      最近更新 更多