如何使用 Laravel 5 将嵌套对象插入 MongoDB? [英] How to insert nested objects into MongoDB with Laravel 5?

查看:48
本文介绍了如何使用 Laravel 5 将嵌套对象插入 MongoDB?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Laravel 5 和基于 MongoDB 的 Eloquent Jenssegers 来开发 API 来保存和获取数据.我有一个名为 Player 的对象,内部还有其他嵌套对象.

I'm using Laravel 5 and MongoDB based Eloquent Jenssegers to develop an API to save and get data. I have a object called Player and inside I have other nested objects.

例如:

{
  "idPlayer": "1",
  "name": "John",
  "lastname": "Doe",
  "stats": {
    "position": "lorem",
    "profile": "ipsum",
    "technique": {
      "skill": 1
    }
  }
}

使用 Postman 测试我可以毫无问题地插入 "idPlayer""name""lastname",但我不能不知道如何在 Player 对象中插入统计数据.

Using Postman to test I've could insert "idPlayer", "name" and "lastname" without problems, but I couldn't figure out how to insert stats inside the Player object.

这是我试过的:

PlayerController.php

PlayerController.php

public function store(Request $request)
{
    $player->name= $request->input('name');
    $player->lastname = $request->input('lastname');
    $player->save();
    return response()->json($player);
}

为了插入统计信息,我尝试在 store 函数中执行以下操作:

And to insert stats I've tried to do something like this inside the store function:

$player->stats = $request->input('position');
$player->stats = $request->input('profile');

但我在响应中得到 "Stats:null" 并且姓名和姓氏插入正常.

But I get "Stats:null" on response and the name and lastname inserts ok.

我希望像上面显示的 Player 对象那样插入数据.

I expect to insert the data just as the Player object shown above.

推荐答案

使用键创建数组.

public function store(Request $request)
{
    $player->name = $request->input('name');
    $player->lastname = $request->input('lastname');
    $player->stats = [
      'position' => $request->input('stats.position'),
      'profile' => $request->input('stats.profile'),
    ];
    $player->save();
    return response()->json($player);
}

  • 有关PHP 数组的更多数据.
  • Laravel 请求中检索输入.
    • More data about PHP arrays.
    • Retrieving input from Laravel Requests.
    • 这篇关于如何使用 Laravel 5 将嵌套对象插入 MongoDB?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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