我在Laravel中使用MongoDB。我有一个叫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"
}
]
我正在尝试制作一个将细节添加到上述文档中的specifics数组的函数。
这是我的请求正文
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);
}
但是当我打这个电话时,我得到了错误
CategoryController.php第101行中的ErrorException:间接修改重载属性App \ Category :: $ specifics无效
请帮助我解决此问题。
我正在为MongoDB使用https://github.com/jenssegers/laravel-mongodb这个软件包。
由于在Eloquent中实现访问模型属性的方式,因此当您访问$ category-> specifics时,将调用魔术__get()方法,该方法返回该属性值的副本。因此,当您向该副本添加元素时,您只是在更改副本,而不是原始属性的值。这就是为什么您会收到一条错误消息,指出无论您在做什么,都不会产生任何效果。
如果要向$ category-> specifics数组中添加新元素,则需要通过以setter方式访问属性来确保使用了魔术__set(),例如:
$category->specifics = array_merge($category->specifics, $this->request->get('specifics'));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句