【发布时间】:2017-01-02 21:47:40
【问题描述】:
我有两个实体,其中每个 Product 可以有 oneToMany Aspect 实体与之关联。
由于 Products 表非常大,我使用 bigint 作为它的 ID,因此,我正在尝试为 Aspect 构建一个复合键以使用 Product ID 和 smallint (我试图用Product#aspectsCount 增加)。但是,我收到了 ContextErrorException:
注意:未定义索引:方面
我的实体如下(我最初尝试 indexBy="id") 是为了使用 Aspect 的数字 ID,但我似乎也无法使其正常工作,因此使用下面的 name与我在网上阅读的示例更一致):
产品实体
class Product
{
/**
* @ORM\Column(type="bigint", options={"unsigned"=true})
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\OneToMany(targetEntity="Aspect", mappedBy="product", cascade={"all"}, indexBy="name")
*/
private $aspects;
/**
* @ORM\Column(name="aspectsCount", type="smallint", options={"unsigned"=true}, nullable=false)
*/
private $aspectsCount;
public function __construct()
{
$this->aspects = new ArrayCollection();
$this->setCreateDT(new \Datetime);
$this->setUpdateDT(new \Datetime);
$this->aspectsCount = 0;
}
/**
* Add aspect
*
* @param \AppBundle\Entity\Aspect $aspect
*
* @return product
*/
public function addAspect($name)
{
$aspect = new Aspect($this, $name);
$this->aspects[$name] = $aspect;
return $this;
}
/**
* Remove aspect
*
* @param \AppBundle\Entity\Aspect $aspect
*/
public function removeAspect(\AppBundle\Entity\Aspect $aspect)
{
$this->aspects->removeElement($aspect);
$this->setAspectsCount($this->aspectsCount-1);
}
}
方面实体
class Aspect
{
/**
* @ORM\Id
* @ORM\ManyToOne(targetEntity="Product", inversedBy="aspects")
* @ORM\JoinColumn(name="product_id", referencedColumnName="id")
*/
private $product;
/**
* @ORM\Id
* @ORM\Column(type="smallint", options={"unsigned"=true}, nullable=false)
*/
private $id;
/**
* @ORM\Column(name="name", type="text")
*/
private $name;
public function __construct($product, $name)
{
$product->setAspectsCount($product->getAspectsCount()+1);
$this->product = $product;
$this->id = $product->getAspectsCount();
$this->name = $name;
}
}
通过扩展,如果另一个表应该存在于“下方”Aspect,如何建立这样的关联? Doctrine 会在内部处理复合键还是我需要执行以下操作:
class Aspect_subtype
{
/**
* @ORM\Id
* @ORM\ManyToOne(targetEntity="Product")
* @ORM\JoinColumn(name="product_id", referencedColumnName="id")
*/
private $product;
/**
* @ORM\Id
* @ORM\ManyToOne(targetEntity="Aspect")
* @ORM\JoinColumn(name="aspect_id", referencedColumnName="id")
*/
private $aspect;
/**
* @ORM\Id
* @ORM\Column(type="smallint", options={"unsigned"=true}, nullable=false)
*/
private $id;
/**
* @ORM\Column(name="name", type="text")
*/
private $name;
// etc...
}
【问题讨论】:
-
Notice: Undefined index: aspect哪里出错了 -
我正在使用 FOSRestBundle,当我请求使用 Product 实体的路由时,此错误会在 JSON 中返回
-
他们是你的完整实体吗?如果不发布它们以及发布您的 FOSBundle 代码以进行插入。我也可以学到一些新东西
-
因为我看到
$this->setCreateDT(new \Datetime); $this->setUpdateDT(new \Datetime);和 `$product->setAspectsCount($product->getAspectsCount()+1);` 但它们没有在任何地方定义 -
我“很遗憾”正在度假,所以无法发布完整的代码 - 但这是给我带来问题的简化代码。您提到的
getAspectsCount()+1(及相关)代码用于在每个产品中存储一个计数器,以便项目的每个新方面都有一个递增的 ID 整数
标签: doctrine-orm symfony composite-primary-key