[英]symfony2 doctrine manytoone relationship
I believe it's that there must be a simple solution for my issue but I can't get that to work and I'm not sure why. 我认为这是必须为我的问题提供一个简单的解决方案,但我无法解决该问题,而且我不确定为什么。
Scenario: I've got 2 entities: Bike and Review, relationship is OneToMany: 场景:我有2个实体:Bike和Review,关系是OneToMany:
/**
* Bike
*
* @ORM\Entity(repositoryClass="BikeRepository")
* @ORM\HasLifecycleCallbacks
* @ORM\Table(name="bike")
*/
class Bike
{
...
/**
* @var string
*
* @ORM\OneToMany(targetEntity="Review", mappedBy="bike", cascade={"persist"}, fetch="EXTRA_LAZY")
*/
private $reviews;
...
}
/**
* Review
*
* @ORM\Entity(repositoryClass="ReviewRepository")
* @ORM\Table(name="review")
* @ORM\HasLifecycleCallbacks()
*/
class Review
{
...
/**
* @var integer
*
* @ORM\ManyToOne(targetEntity="Bike", inversedBy="reviews", fetch="EXTRA_LAZY")
* @ORM\JoinColumn(name="bike_id", referencedColumnName="id")
*/
private $bike;
....
}
Getters and setters has been generated by doctrine. 吸气剂和二传手是由学说产生的。
On the frontend I've got a form where bike is as a hidden field because there is an autocomplete field with ajax request. 在前端,我有一个表单,其中Bike作为隐藏字段,因为有一个带有Ajax请求的自动填充字段。 So in the controller if $form->isValid() I'm getting bike id from the hidden field, search database for that bike and set bike as below:
因此,在控制器中,如果$ form-> isValid()从隐藏字段中获取自行车ID,请搜索该自行车的数据库,并将自行车设置如下:
if ($form->isValid()) {
if ($bikeId) {
$bike = $this->em->getRepository('BikeBundle:Bike')->findOneBy(array('id' => $bikeId));
$review->setBike($bike);
}
$this->em->persist($review);
$this->em->flush();
}
And this is always giving me NULL in the database for bike_id. 这总是给我bike_id数据库中的NULL。 Any idea what could be wrong?
知道有什么问题吗? I have tried to dump $review before persist and I can get the bike details so I don't know what's going wrong.
我试图在坚持之前转储$ review,我可以得到自行车的详细信息,所以我不知道出了什么问题。 In the entity setBike() method I can get any value of that Bike object except getId() is returning NULL.
在实体setBike()方法中,除了getId()返回NULL之外,我可以获取该Bike对象的任何值。
Thanks for any help. 谢谢你的帮助。
you don't need to persist an existing entity, so you can just save your entity like 您不需要保留现有实体,因此只需保存您的实体,例如
$review->setBike($bike);
$ review-> setBike($ bike); $this->em->flush();
$ this-> em-> flush();
try to check if doctrine really returns any entities..I'm afraid if it doesn't return Bike entity 尝试检查该学说是否真的返回任何实体。.恐怕它是否不返回Bike实体
UPD: Also try to check the namespace of Bike Entity class. UPD:还尝试检查Bike Entity类的名称空间。 It seems like it is wrong in your case, because usually it looks like "AcmeBikeBundle:Bike"
您的情况似乎不对,因为通常看起来像“ AcmeBikeBundle:Bike”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.