Created
April 20, 2011 05:13
-
-
Save cobbweb/930428 to your computer and use it in GitHub Desktop.
How to move embedded documents between parent documents in Doctrine ODM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Doctrine\ODM\MongoDB\Tests\Functional; | |
use Doctrine\Common\Collections\ArrayCollection, | |
Documents\Functional\EmbeddedTestLevel0, | |
Documents\Functional\EmbeddedTestLevel1, | |
Documents\Functional\EmbeddedTestLevel2; | |
class MoveEmbeddedDocuments extends \Doctrine\ODM\MongoDB\Tests\BaseTest | |
{ | |
public function testMoveEmbeddedDocuments() | |
{ | |
$repo = $this->dm->getRepository(__NAMESPACE__.'\Category'); | |
$category1 = new Category; | |
$category2 = new Category; | |
$post1 = new Post('Post 1'); | |
$category1->addPost($post1); | |
$this->dm->persist($category1); | |
$this->dm->persist($category2); | |
$this->dm->flush(); | |
$category1 = $repo->find($category1->getId()); | |
$category2 = $repo->find($category2->getId()); | |
$post = $category1->getPost('Post 1'); | |
$this->assertEquals('Post 1', $post->getTitle()); | |
$category1->movePostToCategory($post, $category2); | |
$this->dm->flush(); | |
$this->dm->clear(); | |
$category1 = $repo->find($category1->getId()); | |
$category2 = $repo->find($category2->getId()); | |
$this->assertEquals(0, $category1->getPosts()->count()); | |
$this->assertEquals(1, $category2->getPosts()->count()); | |
$post = $category2->getPosts()->first(); | |
$this->assertInstanceOf(__NAMESPACE__.'\Post', $post); | |
$this->assertEquals('Post 1', $post->getTitle()); | |
} | |
} | |
/** @Document */ | |
class Category | |
{ | |
/** @Id */ | |
private $id; | |
/** @EmbedMany(targetDocument="Post") */ | |
private $posts; | |
public function __construct() | |
{ | |
$this->posts = new ArrayCollection; | |
} | |
public function getId() | |
{ | |
return $this->id; | |
} | |
public function addPost(Post $post) | |
{ | |
$this->posts->add($post); | |
} | |
public function deletePost(Post $post) | |
{ | |
$this->posts->removeElement($post); | |
} | |
public function movePostToCategory(Post $post, Category $category) | |
{ | |
$category->addPost(clone $post); | |
$this->deletePost($post); | |
} | |
public function getPost($name) | |
{ | |
return $this->posts->filter(function($post) use($name){ | |
return $post->getTitle() === $name; | |
})->first(); | |
} | |
public function getPosts() | |
{ | |
return $this->posts; | |
} | |
} | |
/** @EmbeddedDocument */ | |
class Post | |
{ | |
private $title; | |
public function __construct($title) | |
{ | |
$this->title = $title; | |
} | |
public function getTitle() | |
{ | |
return $this->title; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment