Pet*_*ter 6 php symfony doctrine-orm
曾几何时,在黑暗的深渊中,有一些人在Symfony的土地深处,有一个沮丧的程序员.他尝试过并试过但不知何故,邪恶的教义一次又一次地被打击.还有恶棍Joins,Associative tables并One-to-Many/Many-to-One给他一个艰难的时刻.然后,在一个傍晚StackOverflow,它的社区来救援.
足够的童话故事.我的问题是我有三个表应该都引用同一个表来获取附件.
- Mail
- Order
- Ticket
Run Code Online (Sandbox Code Playgroud)
这三个实体中的每一个都可以有附件.所以我创建了一个附件实体.
现在,我的数据库包含以下内容
Table: mails
- id
- from
- to
- message
Table attachments
- id
- name
- path
Table: orders
- id
- ...
Table: tickets
- id
- name
- description
- ...
Table attachment_associations
- id
- type
- parent_id
- attachment_id
Run Code Online (Sandbox Code Playgroud)
我想做的是能够将订单,票据和邮件映射到相同的附件表.
但是,我坚持如何在学说中做到这一点.
我尝试使用以下方法.这确实得到了我正在寻找的记录.但我不知道如何使用此方法自动创建,更新或删除关联表(连接表)中的记录.
/**
* @ORM\ManyToMany(targetEntity="\...\...\Entity\Attachment")
* @ORM\JoinTable(name="attachment_associations",
* joinColumns={@ORM\JoinColumn(name="parentId", referencedColumnName="id")},
* inverseJoinColumns={
* @ORM\JoinColumn(name="attachmentId", referencedColumnName="id")
* }
* )
*/
protected $attachments;
Run Code Online (Sandbox Code Playgroud)
如果我删除邮件,订单或票证,是否也会删除所有相应的附件?
一种非常简单的方法是使用其他实体扩展的类表继承来实现映射的超类。
尽管存在性能影响,您必须针对您的特定项目进行判断。
这是一个简单的例子:
映射的超类
<?php
namespace AcmeBundle\Model;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity()
* @ORM\InheritanceType("JOINED")
* @ORM\DiscriminatorColumn(name="type", type="string")
*/
abstract class SuperClass
{
/**
* @var int
*
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
protected $id;
/**
* @var Attachment[]
*
* @ORM\ManyToMany(targetEntity="Attachment", mappedBy="parents")
*/
protected $attachments = [];
/**
* Constructor
*/
public function __construct()
{
$this->attachments = new ArrayCollection();
}
// put setters/getters for $attachments here
}
Run Code Online (Sandbox Code Playgroud)
附件管理关联。
<?php
namespace AcmeBundle\Model;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity()
*/
class Attachment
{
/**
* @var int
*
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @var SuperClass
*
* @ORM\ManyToMany(targetEntity="SuperClass", inversedBy="attachments")
*/
private $parents;
/**
* Constructor
*/
public function __construct()
{
$this->parents = new ArrayCollection();
}
}
Run Code Online (Sandbox Code Playgroud)
该实体只是扩展超类
<?php
namespace AcmeBundle\Model;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity()
*/
class Ticket extends SuperClass
{
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
215 次 |
| 最近记录: |