【问题标题】:can't update json column using Laravel eloquent model无法使用 Laravel 雄辩模型更新 json 列
【发布时间】:2021-06-01 22:41:09
【问题描述】:

我正在尝试测试 Eloquent 模型的更新...

 /** @test */
  public function updates_to_json_fields_are_logged()
    {
      $data = json_encode(["json_key" => "old_value"]);
      $individual = Individual::factory()->create([
        "information" => $data
      ]);
      json_decode($individual->information)->json_key = "new_value";
      $individual->save();
      
      echo(var_dump($individual));

      $this->assertTrue(false);

  }

information 是一个 json 列。

当我保存$individual 后登录时,"information->json_key" 的值仍然是"old_value"。谁能告诉我为什么?

【问题讨论】:

  • 您的代码完全按照您的编写。在json_decode 返回的新对象上分配"new_value"。存储在$individual 中的对象没有发生任何变化
  • @N69S。如何更改原点对象?
  • 我在下面添加了一个答案,它对你有用吗?

标签: mysql json laravel eloquent


【解决方案1】:

改变 $individual 对象而不用花哨的分配

/** @test */
  public function updates_to_json_fields_are_logged()
    {
      $data = json_encode(["json_key" => "old_value"]);
      $individual = Individual::factory()->create([
        "information" => $data
      ]);
      $decodedInformation = json_decode($individual->information);
      $decodedInformation->json_key = "new_value";
      $individual->information = json_encode($decodedInformation);
      $individual->save();
      
      echo(var_dump($individual));

      $this->assertTrue(false);

  }

【讨论】:

    【解决方案2】:

    你没有改变原来的$individual对象,而是json_decode()的结果。

    【讨论】:

    • @mm。那么如何更改原始对象呢?
    猜你喜欢
    • 2021-08-11
    • 2014-08-03
    • 2017-09-23
    • 2016-02-27
    • 2015-08-15
    • 1970-01-01
    • 2016-09-27
    • 2016-05-08
    • 1970-01-01
    相关资源
    最近更新 更多