【问题标题】:How to deserialize a Laravel Eloquent model, i.e. reverse toArray(), attributesToArray() or toJson()?如何反序列化 Laravel Eloquent 模型,即反向 toArray()、attributesToArray() 或 toJson()?
【发布时间】:2021-10-05 02:06:15
【问题描述】:

Laravel serialization documentation 详细描述了如何获取 Eloquent 模型的数组/JSON 表示。

但是,它目前并没有说要扭转这一点:从数组/JSON 中获取 Eloquent 模型。

我该怎么做?谢谢!

【问题讨论】:

    标签: laravel serialization eloquent orm


    【解决方案1】:

    您必须创建一个模型实例并影响您的数据,例如,假设您有一个用户模型的数组表示,如下所示:

    $user = [
        "name" => "foo",
        "age" => 40
    ]
    
    

    那么你将不得不像这样创建你的模型:

    $user = User::create($user);
    
    //or
    
    $user = new User;
    $user->name = $user["name"];
    $user->age  = $user["age"];
    $user->save()
    

    【讨论】:

      猜你喜欢
      • 2015-04-10
      • 2014-03-02
      • 1970-01-01
      • 1970-01-01
      • 2017-04-13
      • 2017-12-26
      • 1970-01-01
      • 2014-05-08
      • 1970-01-01
      相关资源
      最近更新 更多