【发布时间】:2012-04-24 17:04:29
【问题描述】:
如何使用 Symfony 2 和 Doctrine 在实体之间创建关系?我只能创建独立实体。也许有人可以帮助我使用实体生成器解决这个问题?我想:
- 创建两个实体:帖子和类别。帖子是类别的一部分。
- 创建标签实体:一个帖子可以有很多标签。
【问题讨论】:
如何使用 Symfony 2 和 Doctrine 在实体之间创建关系?我只能创建独立实体。也许有人可以帮助我使用实体生成器解决这个问题?我想:
【问题讨论】:
这里的 Symfony2 文档中介绍了一个实际示例:
http://symfony.com/doc/current/book/doctrine.html#entity-relationships-associations
详细说明,以第一个示例为例,您需要在您的Category 对象和您的Post 对象之间创建OneToMany 关系:
Category.php:
<?php
namespace Your\CustomBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* @ORM\Table(name="category")
* @ORM\Entity()
*/
class Category
{
/**
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\OneToMany(targetEntity="Post", mappedBy="category")
*/
public $posts;
/**
* Constructor
*/
public function __construct()
{
$this->posts = new ArrayCollection();
}
/**
* @return integer
*/
public function getId()
{
return $this->id;
}
}
Post.php
<?php
namespace Your\CustomBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Table(name="post")
* @ORM\Entity()
*/
class Post
{
/**
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity="Category", inversedBy="posts")
*/
public $category;
/**
* @return integer
*/
public function getId()
{
return $this->id;
}
}
这应该可以帮助您入门。我刚刚写了这个,所以可能会有错误:s
为了简洁起见,我在此处公开属性 $posts 和 $category; 但是可能会建议您将这些设为私有并将 setter/getter 添加到您的类中。
另请注意,$posts 是一个类似数组的 Doctrine ArrayObject 类,特别适用于聚合实体,具有 $category->posts->add($post) 等方法。
有关更多详细信息,请参阅 Doctrine 文档中的关联映射。您可能需要在Posts 和Tags 之间建立ManyToMany 关系。
希望这会有所帮助:)
【讨论】:
OneToMany 注释。但是,例如,如果您想显示与某个类别等相关的所有帖子,这将很有用。
您不会与实体生成器本身创建关系。
一旦实体类本身存在(使用实体生成器创建或手动编写),您就可以对其进行编辑以添加关系。
例如,您的帖子有很多标签示例
namespace Your\Bundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Your\Bundle\Entity\Post
*
* @ORM\Table(name="post")
* @ORM\Entity
*/
class Post
{
/**
* @var \Doctrine\ORM\PersistentCollection
*
* @ORM\OneToMany(targetEntity="Tag", mappedBy="post", cascade={"persist"})
*/
private $tags;
}
有关指定关系的更多信息,请参阅Doctrine's Documentation。
【讨论】: