php - Laravel MongoDB 重载属性的间接修改

标签 php mongodb laravel laravel-5

我将 MongoDB 与 Laravel 一起使用。我有一个名为 categories 的集合,其中有一个文档

[
  {
    "_id": "567dc4b4279871d0068b4568",
    "name": "Fashion",
    "images": "http://example.com/1.jpg",
    "specifics": [
      "made"
    ],
    "brands": [
      {
        "name": "Giordano",
        "logo": "http://example.com/"
      },
      {
        "name": "Armani",
        "logo": "http://example.com/"
      }
    ],
    "updated_at": "2015-12-25 22:40:44",
    "created_at": "2015-12-25 22:35:32"
  }
]

我正在尝试创建一个函数,将细节添加到上述文档中的具体数组中。

这是我的请求正文

HTTP: POST
{
    "specifics": [
        "material"
    ]
}

我正在使用以下函数处理此请求

/**
 * Add specs to category
 * @param string $category_id
 * @return Illuminate\Http\JsonResponse
 */
public function addSpecifics($category_id)
{
    $category = $this->category->findOrFail($category_id);
    $category->specifics[] = $this->request->get('specifics');
    $status_code = config('http.UPDATED');
    return response()->json($category->save(), $status_code);
}

但是当我打这个电话时,我得到了

的错误

ErrorException in CategoryController.php line 101: Indirect modification of overloaded property App\Category::$specifics has no effect

请帮我解决这个问题。

我正在为 MongoDB 使用 https://github.com/jenssegers/laravel-mongodb 这个包。

最佳答案

由于 Eloquent 中访问模型属性的实现方式,当您访问 $category->specifics 时,会调用一个神奇的 __get() 方法,该方法返回一个该属性的值。因此,当您向该副本添加元素时,您只是在更改副本,而不是原始属性的值。这就是为什么您会收到一条错误消息,说无论您在做什么,它都不会产生任何效果。

如果你想向 $category->specifics 数组添加一个新元素,你需要确保通过访问属性来使用魔法 __set()以二传手的方式,例如:

$category->specifics = array_merge($category->specifics, $this->request->get('specifics'));

关于php - Laravel MongoDB 重载属性的间接修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34467076/

相关文章:

ruby - 命名空间内的 Mongoid 文档

pagination - 指定分页页面 - Laravel 4

php - 基于多用户角色的路由级中间件

php - 每个 php 都有多个 post 值

php - 允许apache用户通过auth套接字连接到mysql

php - 阿拉伯/波斯数字的 Number_format

当主节点失败时,Mongodb 辅助节点不会成为主节点

php - Preg_match 用于所有特殊字符,密码检查

javascript - MongoDB NodeJS 进程内存不足

使用 php artisan 时,laravel 从自定义 stub 创建模型