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

Zep*_*ram 8 model-binding laravel eloquent

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

整数ID,字符串文本

我如何转换这个JSon:

{ post: { text: 'my text' } }
Run Code Online (Sandbox Code Playgroud)

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

public function store(Post $post)
{
    $post->save();
}
Run Code Online (Sandbox Code Playgroud)

我不打算构建那些能够为我做到这一点的逻辑,但是对于Laravel方式(或者可能是没有一个?我用Google搜索没有相关结果).

Bar*_*zek 12

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

    $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 = \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);
    
    Run Code Online (Sandbox Code Playgroud)


Alb*_*ght 6

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

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

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

一旦我们有了解码的数据,我们就可以创建一个Posteloquent 模型的实例并调用forceFill它:

$post = new Post();
$post->forceFill($innerPost);
$post->save();
Run Code Online (Sandbox Code Playgroud)

这类似于执行以下操作:

$post = new Post();
foreach ($innerPost as $key => $value) {
    $post->$key = $value;
}
$post->save();
Run Code Online (Sandbox Code Playgroud)


Odi*_*sky 0

你能像这样尝试一下吗?

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