我有三个实体:PurchaseOrder,Article和ArticleOrderReference。我需要ArticleOrderReference实体为每个Order to Article Relation提供一个整数值的数量。
所以purchaseOrder可以有很多ArticleOrderReferences。一篇文章也可以有很多ArticleOrderReferences。
我的问题是,例如与具有ID:1的PurchaseOrder有关系的每个ArticleOrderReference可能只有一次相同的Article。所以我不能再次选择同一篇文章了。
在我的FormBuilderType中:
$builder->add('article', 'entity', array(
'class' => 'AcmeAppBundle:Article',
'property' => 'name',
));
$builder->add('amount', 'integer');
我怎么能意识到这一点?
的PurchaseOrder:
class PurchaseOrder{
/** @ORM\OneToMany(targetEntity="ArticleOrderReference", mappedBy="purchaseOrder") */
protected $purchaseOrders;
ArticleOrderReference:
/** @ORM\ManyToOne(targetEntity="Article", inversedBy="articles") */
protected $article;
/** @ORM\ManyToOne(targetEntity="PurchaseOrder", inversedBy="purchaseOrders") */
protected $purchaseOrder;
/**
* @var integer
*
* @ORM\Column(name="amount", type="integer")
*/
private $amount;
文章:
/**
* @var string
*
* @ORM\Column(name="name", type="string", length=255)
*/
private $name;
/** @ORM\OneToMany(targetEntity="ArticleOrderReference", mappedBy="article") */
protected $articles;
控制器:
$articleOrder = new ArticleOrderReference();
$form = $this->createForm(new ArticleOrderType(), $articleOrder);
// process the form on POST
if ($request->isMethod('POST')) {
$form->bind($request);
if ($form->isValid()) {
$purchaseOrder = $this->getDoctrine()
->getRepository('AcmeAppBundle:PurchaseOrder')
->find($id);
if (!$purchaseOrder) {
throw $this->createNotFoundException(
'No order found for id '.$id
);
}
$articleOrder->setPurchaseOrder($purchaseOrder);
$em = $this->getDoctrine()->getManager();
$em->persist($articleOrder);
$em->flush();
return $this->redirect($this->generateUrl('order', array('id' => $id)));
}
}
答案 0 :(得分:0)
您可以使用UniqueEntity constraint确保一个Article
仅通过表格PurchaseOrder
与ArticleOrderReference
相关联一次。
您需要更改ArticleOrderReference
实体,如下所示:
namespace Acme\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
// DON'T forget this use statement!!!
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* @ORM\Entity
* @UniqueEntity({"article", "purchaseOrder"})
*/
class ArticleOrderReference
{
/** @ORM\ManyToOne(targetEntity="Article", inversedBy="articles") */
protected $article;
/** @ORM\ManyToOne(targetEntity="PurchaseOrder", inversedBy="purchaseOrders") */
protected $purchaseOrder;
/**
* @var integer
*
* @ORM\Column(name="amount", type="integer")
*/
private $amount;
// ...
}