我得到了两个实体。 这是第一个有OneToMany的人:
class MarketMain
{
/**
* @var integer
*
* @ORM\Column(name="id", type="bigint", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var \Doctrine\Common\Collections\Collection
*
* @ORM\OneToMany(targetEntity="\Acme\CMSBundle\Entity\MarketLanguage", mappedBy="marketMain", indexBy="langId", cascade="all", orphanRemoval=true, fetch="EXTRA_LAZY")
*/
private $marketLanguage;
}
这是逆转ManyToOne的第二个:
class MarketLanguage
{
/**
* @var integer
*
* @ORM\Column(name="market_id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="NONE")
*/
private $marketId = 0;
/**
* @var integer
*
* @ORM\Id
* @ORM\Column(name="lang_id", type="integer", nullable=false)
*/
private $langId = 1;
/**
* @var string
*
* @ORM\Column(name="name", type="string", length=200, nullable=true)
*/
private $name;
/**
* @var \Acme\CMSBundle\Entity\MarketMain
*
* @ORM\ManyToOne(targetEntity="\Acme\CMSBundle\Entity\MarketMain", inversedBy="marketLanguage")
* @ORM\JoinColumn(name="market_id", referencedColumnName="id")
*/
private $marketMain;
}
我想保存这样的实体:
$em = $this->getDoctrine()->getManager();
$marketMain = new MarketMain();
$marketLanguage = new ArrayCollection();
$marketLanguage->set(1,new MarketLanguage());
$marketLanguage->set(2,new MarketLanguage());
$marketLanguage->set(3,new MarketLanguage());
$marketMain->setMarketLanguage($marketLanguage);
foreach ($marketMain->getMarketLanguage() as $market_language)
{
$market_language->setMarketMain($marketMain);
}
$em->persist($marketMain);
$em->flush();
foreach ($marketMain->getMarketLanguage() as $market_language)
{
$market_language->setName("Default name for MarketMain entity id:".$marketMain->getId());
}
$em->flush();
但是在第二次刷新之后,我的MarketLanguage实体没有更新,在学说查询日志中,我看到MarketLanguage实体在与MarketMain持续存在后没有关系。请不要说我必须在持久化之前设置MarketLanguage名称,因为我必须将刷新的ID添加到该名称。
这是在第二次刷新中执行更新的查询(来自学说日志):
"START TRANSACTION" [] []
UPDATE market_language SET name = ? WHERE market_id = ? AND lang_id = ? ["Default name for MarketMain entity 15",0,"1"] []
"COMMIT" [] []
答案 0 :(得分:0)
$ marketMain = new MarketMain();您正在创建新实例
$marketMain->getMarketLanguage()
将返回空数组,也许您应该从数据库查询所有MarketLanguages然后将它们分配给MarketMain?
$langs = $em->getRepositiory('Bundle:MarketLanguage')->findAll()
foreach ($langs as $market_language)
{
$market_language->setMarketMain($marketMain);
}
$em->persist($marketMain);
$em->flush();
编辑:
所以试试这个:
$ml1 = new MarketLanguage();
$ml2 = new MarketLanguage();
$ml3 = new MarketLanguage();
$marketLanguage->set(1,$ml1);
$marketLanguage->set(2,$ml2);
$marketLanguage->set(3,$ml3);
$marketMain->setMarketLanguage($marketLanguage);
foreach ($marketMain->getMarketLanguage() as $market_language)
{
$market_language->setMarketMain($marketMain);
}
$em->persist($marketMain);
$em->persist($ml1);
$em->persist($ml2);
$em->persist($ml3);
$em->flush();
答案 1 :(得分:0)
看起来问题是因为MarketLanguage ID已修复,因为:
private $marketId = 0;
请在没有= 0
编辑:由于您使用“无”ID生成策略,您必须手动为MarketLanguage实体分配ID。见doc