Laravel Mongodb 嵌入对象中的嵌入对象
Laravel Mongodb embedded object in embedded object
我有一个带有 embedsMany 模型评论的模型新闻,在模型评论中我有 embedsMany 模型回复
当我这样做时:
$new = News::create(["title"=>"Simple new", "body"=>"this is a simple news"]);
$comment = $new->comments()->create(["subject"=>"comment 1", "body"=>"my comment"]);
插入成功,数据库中的数据为:
{
"title" : "Simple new",
"body" : "this is a simple news",
"_id" : ObjectId("5569b157bed33066220041ac"),
"comments" : [
{
"subject" : "comment 1",
"body" : "my comment",
"_id" : ObjectId("5569cc28bed330693eb7acd9")
}
]
}
但是当我这样做时:
$reply = $comment->replies()->create(["subject"=>"reply to comment 1", "body"=>"my reply"]);
数据库是:
{
"title" : "Simple new",
"body" : "this is a simple news",
"_id" : ObjectId("5569b157bed33066220041ac"),
"comments" : [
{
"subject" : "comment 1",
"body" : "my comment",
"_id" : ObjectId("5569cc28bed330693eb7acd9"),
"replies" : {
"0" : {
"subject" : "reply to comment 1",
"body" : "my reply",
"_id" : ObjectId("5569cc33bed330693eb7acda"
}
}
}
]
}
删除回复无效
解决方案一:
在jenssegers/laravel-mongodb 框架中,您可以使用 push 或 update 方法将文档插入数组。注:早期版本没有push方法
方案二:(推荐)
Mongodb 使用模式基础框架(即 nosql,无模式数据库)是错误的,建议使用 php 的官方 Mongodb 框架:
http://docs.mongodb.org/ecosystem/drivers/php
为了加快查询速度,您可以使用索引。
在此解决方案中,您可以使用此数据结构:
{
"_id" : ObjectId("5577d8a419e5eae7ae17a058"),
"name" : "My New",
"comments" : {
"5577d8c419e5eae7ae17a059": {
"subject" : "My Comment",
"body" : "BODY",
"replies" : {
"5577d91619e5eae7ae17a05b": {
"subject" : "My Reply",
"body" : "BODY"
}
}
}
}
我有一个带有 embedsMany 模型评论的模型新闻,在模型评论中我有 embedsMany 模型回复
当我这样做时:
$new = News::create(["title"=>"Simple new", "body"=>"this is a simple news"]);
$comment = $new->comments()->create(["subject"=>"comment 1", "body"=>"my comment"]);
插入成功,数据库中的数据为:
{
"title" : "Simple new",
"body" : "this is a simple news",
"_id" : ObjectId("5569b157bed33066220041ac"),
"comments" : [
{
"subject" : "comment 1",
"body" : "my comment",
"_id" : ObjectId("5569cc28bed330693eb7acd9")
}
]
}
但是当我这样做时:
$reply = $comment->replies()->create(["subject"=>"reply to comment 1", "body"=>"my reply"]);
数据库是:
{
"title" : "Simple new",
"body" : "this is a simple news",
"_id" : ObjectId("5569b157bed33066220041ac"),
"comments" : [
{
"subject" : "comment 1",
"body" : "my comment",
"_id" : ObjectId("5569cc28bed330693eb7acd9"),
"replies" : {
"0" : {
"subject" : "reply to comment 1",
"body" : "my reply",
"_id" : ObjectId("5569cc33bed330693eb7acda"
}
}
}
]
}
删除回复无效
解决方案一:
在jenssegers/laravel-mongodb 框架中,您可以使用 push 或 update 方法将文档插入数组。注:早期版本没有push方法
方案二:(推荐)
Mongodb 使用模式基础框架(即 nosql,无模式数据库)是错误的,建议使用 php 的官方 Mongodb 框架:
http://docs.mongodb.org/ecosystem/drivers/php
为了加快查询速度,您可以使用索引。
在此解决方案中,您可以使用此数据结构:
{
"_id" : ObjectId("5577d8a419e5eae7ae17a058"),
"name" : "My New",
"comments" : {
"5577d8c419e5eae7ae17a059": {
"subject" : "My Comment",
"body" : "BODY",
"replies" : {
"5577d91619e5eae7ae17a05b": {
"subject" : "My Reply",
"body" : "BODY"
}
}
}
}