重载属性Laravel MongoDB的间接修改 [英] Indirect Modification of Overloaded Property Laravel MongoDB
问题描述
我正在将MongoDB与Laravel结合使用.我有一个名为categories
的集合,其中有一个文档
I am using MongoDB with Laravel. I have a collection called categories
which has one document
[
{
"_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数组的函数.
I am trying to make a function that add specifics to the specifics array in the above document.
这是我的请求正文
HTTP: POST
{
"specifics": [
"material"
]
}
我正在使用以下功能处理该请求
And i am handling this request with the following function
/**
* 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);
}
但是当我打这个电话时,我得到
But when i hit this call, I get error of
CategoryController.php第101行中的ErrorException:间接 重载属性App \ Category :: $ specifics的修改没有 效果
ErrorException in CategoryController.php line 101: Indirect modification of overloaded property App\Category::$specifics has no effect
请帮助我解决此问题.
我正在使用 https://github.com/jenssegers/laravel-mongodb 用于MongoDB.
I am using https://github.com/jenssegers/laravel-mongodb this package for MongoDB.
推荐答案
由于在Eloquent中如何实现访问模型属性,当您访问 $ category-> specifics 时,魔术 __ get ()方法被调用,该方法返回该属性值的副本.因此,当您向该副本添加元素时,您只是在更改副本,而不是原始属性的值.这就是为什么您会收到一条错误消息,指出无论您在做什么,都不会产生任何效果.
Due to how accessing model attributes is implemented in Eloquent, when you access $category->specifics, a magic __get() method is called that returns a copy of that attribute's value. Therefore, when you add an element to that copy, you're just changing the copy, not the original attribute's value. That's why you're getting an error saying that whatever you're doing, it won't have any effect.
如果要向
If you want to add a new element to $category->specifics array, you need to make sure that the magic __set() is used by accessing the attribute in a setter manner, e.g.:
$category->specifics = array_merge($category->specifics, $this->request->get('specifics'));
这篇关于重载属性Laravel MongoDB的间接修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!