我收到此错误:
完整性约束违规:1048 列 'user_id' 不能为空
当我尝试在控制器中使用地址保存用户时:
$em = $this->getDoctrine()->getEntityManager();
$user=new User();
$adr=new Address();
$user->getAddresses()->add($adr);
/* i add something missing here */
$form =$this->createForm(new UserForm(),$user);
if ('POST' == $request->getMethod()) {
$form->bindRequest($request);
if ($form->isValid()) {
$em->persist($user);
$em->flush();
return $this->redirect($this->generateUrl('homepage'));
}
}
好吧,这些是我的实体类,用户和地址:
public class User {
/**
* @var integer $id
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var Address
*
* @ORM\OneToMany(targetEntity="Address", mappedBy="user", cascade={"all"})
* @ORM\OrderBy({"zipCode" = "ASC"})
*/
protected $addresses;
}
public class Address{
/**
* @var User
*
* @ORM\ManyToOne(targetEntity="User",inversedBy="addresses")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="user_id", referencedColumnName="id")
* })
*/
private $user;
}
在表单类中:
$builder->add('addresses', 'collection', array('type' => new AddressForm()));
在日志中,有以下消息:
INSERT INTO user (email, password, salt, is_active, username, description, user_type_id,partner_type_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?){"1":"test@yahoo.ca","2":"ttttt","3":null,"4":null,"5":null,"6":"sdfadf","7":3,"8":9})
当它尝试保存地址时:
INSERT INTO address (Number, voie_name, additional_address, zip_code, city, cedex, created_at, tel, loc_lat, loc_lng, voie_id, user_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ({"1":"12","2":"asdf","3":"sdfasdf","4":"69001","5":"Lyon 1er","6":null,"7":null,"8":"04 65 46 46 54","9":null,"10":null,"11":4,"12":null})
注意"12":null
,这很奇怪,因为 Doctrine 已经保存了用户。