我有以下文件: 使用 EmbedMany 订购 Orderlines 使用 EmbedOne 产品订购
我有一个现有的订单,我想在其中添加一个新的订单行,但是当我获取一个现有的订单并向其中添加新的订单行时,我添加了两个新的订单行。
来自我的控制器的代码:
$dm = $this->get('doctrine_mongodb')->getManager();
// Get the session id for current user
$sessionId = $this->get('session')->getId();
// Fetch an existing order
$order = $dm->getRepository('AcmeDemoBundle:Order')
->findOneBy(array('session_id' => $sessionId));
// Create a new product
$product = new Product();
$product->setTitle('Product title');
// Create an orderline
$orderline = new Orderline();
$orderline->setProduct($product);
$orderline->setQuantity(1);
// Add newly created orderline to the order
$order->addOrderlines($orderline);
$dm->persist($orderline);
$dm->flush();
Doctrine 生成的 MongoDB 查询:
use test_database;
db.Order.find({ "session_id": "ransbtpa63cdbp5vp7fqs2pma5" });
db.Product.insert({ "00000000723450f000000000b20415bf": { "_id": ObjectId("50fc67348e97f4d119000002"), "title": "Product title" } });
db.Orderline.insert({ "000000007234500d00000000b20415bf": { "_id": ObjectId("50fc67348e97f4d119000003"), "product": { "_id": ObjectId("50fc67348e97f4d119000002"), "title": "Product title" }, "quantity": 1 } });
db.Order.update({ "_id": ObjectId("50fc62a18e97f44f1d000002") }, { "$set": { "orderlines.5.product.title": "Product title", "orderlines.5.quantity": 1 } });
db.Order.update({ "_id": ObjectId("50fc62a18e97f44f1d000002") }, { "$pushAll": { "orderlines": [ { "_id": ObjectId("50fc67348e97f4d119000003"), "product": { "_id": ObjectId("50fc67348e97f4d119000002"), "title": "Product title" }, "quantity": 1 } ] } });
并从 MongoDB 订购文档(查询添加的订单行 1 和 2):
[_id] => MongoId Object (
[$id] => 50fc62a18e97f44f1d000002
)
[orderlines] => Array (
[0] => Array (
[_id] => MongoId Object (
[$id] => 50fc62a18e97f44f1d000001
)
[product] => Array (
[_id] => MongoId Object (
[$id] => 50fc62a18e97f44f1d000000
)
[title] => Product title
)
[quantity] => 1
)
[1] => Array (
[product] => Array (
[title] => Product title
)
[quantity] => 1
)
[2] => Array (
[_id] => MongoId Object (
[$id] => 50fc62d08e97f4f41d000002
)
[product] => Array (
[_id] => MongoId Object (
[$id] => 50fc62d08e97f4f41d000001
)
[title] => Product title
)
[quantity] => 1
)
)
[session_id] => ransbtpa63cdbp5vp7fqs2pma5
我认为问题是由第一个带有 $set 的 db.Order.insert 查询引起的,然后是 $pushAll。我怎样才能摆脱过多的查询,为什么 Doctrine 会生成它?