我有一个模型新闻与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"]);
DB是:
{
"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"
}
}
}
]
}
并删除回复不起作用
答案 0 :(得分:2)
解决方案1:
在jenssegers / laravel-mongodb框架中,您可以使用push或update方法将文档插入到数组中。注意:早期版本中不存在push方法。
解决方案2:(推荐)
使用Mongodb的架构基础框架(即nosql,架构少数据库)是错误的,建议使用官方的Mongodb框架用于php:
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"
}
}
}
}