如何将 json 转换为 Laravel Eloquent 模型? [英] How can I convert json to a Laravel Eloquent Model?

查看:42
本文介绍了如何将 json 转换为 Laravel Eloquent 模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个名为 Post 的 Eloquent 模型,并且 mysql 表有:

if I have an Eloquent Model called Post, and the mysql table has:

整数 ID,字符串文本

integer ID, string Text

我如何转换这个 JSon:

How do I convert this JSon:

{ post: { text: 'my text' } }

到相关的 Post 对象,一旦在控制器中接收到,我就可以像这样保存到数据库中:

To the relevant Post object that, once received in the controller, I can save to the database like this:

public function store(Post $post)
{
    $post->save();
}

我不是要构建适合我的逻辑,而是要为 Laravel 方式构建逻辑(或者可能没有?我用谷歌搜索,没有相关结果).

I'm not looking to build the logic that would do that for me, but for the Laravel way (or could it be that there isn't one? I googled it with no relevant results).

推荐答案

  1. 将json转换为数组
  2. 来自阵列的水合物模型

  1. Convert json to array
  2. Hydrate model from array

$data = '{  
            "unique_id_001":{"name":"John","email":"JD@stackoverflow.com"},
            "unique_id_002":{"name":"Ken","email":"Ken@stackoverflow.com"}
          }';
$object = (array)json_decode($data);
$collection = AppUser::hydrate($object);
$collection = $collection->flatten();   // get rid of unique_id_XXX

/*
    Collection {#236 ▼
      #items: array:2 [▼
        0 => User {#239 ▶}
        1 => User {#240 ▶}
      ]
    }
 */
dd($collection);

这篇关于如何将 json 转换为 Laravel Eloquent 模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆