【发布时间】:2019-07-31 20:02:46
【问题描述】:
我正在使用 symfony 4 框架构建一个 CMS,其中您可能有页面或博客等内容模块...
每个模块都有一组内容块,即Page has a OneToMany relation with ContentBlock 和Blog has a OneToMany relation with ContentBlock。
我对教义-orm 完全陌生。不过,我已经做了一个抽象的MappedSuperclass 类,命名为Content:
/** @ORM\MappedSuperclass */
abstract class Content
{
/**
* @var Collection|ContentBlock[]
* @ORM\OneToMany(targetEntity="App\Entity\ContentBlock", mappedBy="id") <- I need to add one more column with a defined value (entity type) which refers to entity name
* @ORM\OrderBy({"sort"="ASC"})
*/
protected $blocks;
public function __construct()
{
$this->blocks = new ArrayCollection();
}
public function addBlock(ContentBlock $block): self
{
if (!$this->blocks->contains($block)) {
$block->setEntityId($this->getId());
$block->setEntity(self::class);
$this->blocks[] = $block;
}
return $this;
}
public function removeBlock(ContentBlock $block): self
{
if (!$this->blocks->contains($block)) {
$this->blocks->removeElement($block);
}
return $this;
}
/**
* @return Collection|ContentBlock[]
*/
public function getBlocks(): Collection
{
return $this->blocks;
}
public function getType(): string
{
return self::class;
}
}
并使内容实体继承自它,如下所示:
/**
* @ORM\Entity(repositoryClass="App\Repository\PageRepository")
*/
class Page extends Content
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @Assert\NotBlank
* @ORM\Column(type="string", length=255, nullable=false)
*/
private $title;
/**
* @ORM\Entity(repositoryClass="App\Repository\BlogRepository")
*/
class Blog extends Content
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @Assert\NotBlank
* @ORM\Column(type="string", length=255, nullable=false)
*/
private $title;
这里是ContentBlock 实体:
class ContentBlock
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
*/
private $entity;
/**
* @ORM\Column(type="integer")
*/
private $entity_id;
// more columns in addition for their setters and getters
我需要知道的是如何定义ContentBlock 和其他实体之间的关系,其中ContentBlock::$entity_id 代表Content::$id,ContentBlock::$entity 代表博客"App\Entity\Blog","App\Entity\Page" 代表博客页面,换句话说“应该定义实体类型”。
【问题讨论】:
标签: php symfony doctrine-orm one-to-many