如何将 json 转换为 Laravel Eloquent 模型?

问题描述 投票:0回答:6

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

整数ID, 字符串文本

如何转换这个 JSon:

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

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

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

我不想构建为我做这件事的逻辑,而是为了 Laravel 方式(或者可能没有这样的逻辑?我用谷歌搜索没有相关结果)。

laravel eloquent model-binding
6个回答
14
投票
  1. 将 json 转换为数组
  2. 从阵列水合模型

    $data = '{  
                "unique_id_001":{"name":"John","email":"[email protected]"},
                "unique_id_002":{"name":"Ken","email":"[email protected]"}
              }';
    $object = (array)json_decode($data);
    $collection = \App\User::hydrate($object);
    $collection = $collection->flatten();   // get rid of unique_id_XXX
    
    /*
        Collection {#236 ▼
          #items: array:2 [▼
            0 => User {#239 ▶}
            1 => User {#240 ▶}
          ]
        }
     */
    dd($collection);
    

7
投票

fill
看起来像你想要的方法。为了避免将每个属性添加到
$filled
数组(如果您想使用
fill
方法,则需要这样做),您可以使用
forceFill
方法

它接受属性的关联数组,因此必须对 JSON 进行解码,并且我们必须获取内部

post
键:

$rawJson = "{ post: { text: 'my text' } }";
$decodedAsArray = json_decode($rawJson, true);
$innerPost = $decodedAsArray['post'];

一旦我们获得了解码后的数据,我们就可以创建

Post
雄辩模型的实例并在其上调用
forceFill

$post = new Post();
$post->forceFill($innerPost);
$post->save();

这类似于做:

$post = new Post();
foreach ($innerPost as $key => $value) {
    $post->$key = $value;
}
$post->save();

4
投票

只需将其转为数组并填充一个雄辩的

$arr = json_decode($json, true);
$post = new Post;
$post->fill($arr);

4
投票

很简单,如下所示:

$json_post = { "post": { "text": "my text" } };

$post = new Post(
    json_decode($json_post, true)
);

现在,您可以在最$post上运行所有雄辩的方法,例如:

$post->save()

我用 laravel v7.11.0 进行了测试


0
投票

你可以这样尝试吗?

public function store($poststuff)
{
    $post = new Post;
    $post->text = $poststuff['text'];
    $post->save();
}

0
投票

JSON 到模型辅助函数

if (!function_exists('jsonToModel')) {
    function jsonToModel(string $jsonFilePath, Model $model)
    {
        $json = file_get_contents($jsonFilePath);
        $data = json_decode($json);

        foreach ($data as $value) {
            $value = (array) $value;
            $model->updateOrCreate(
                ['id' => $value['id']],
                $value
            );
        }
    }
}

这样使用

jsonToModel(database_path('json/models.json'), new Model());
© www.soinside.com 2019 - 2024. All rights reserved.