当需要在数据库中插入新信息时,我遇到了 Doctrine 2 和 OneToOne 关系的问题。
模型:User.php
<?php
/**
* @Entity @Table(name="user")
**/
class User
{
/** @Id @Column(type="integer") @GeneratedValue **/
protected $id;
/** @Column(type="string") **/
protected $lastname;
/** @Column(type="string") **/
protected $firstname;
/** @Column(type="string") **/
protected $email;
/** @Column(type="integer") **/
protected $status;
/** @Column(type="string") **/
protected $created;
/** @Column(type="integer") **/
protected $created_by;
/**
* @OneToOne(targetEntity="UserAuth", mappedBy="user")
*/
protected $auth;
public function getAuth()
{
return $this->auth;
}
public function setAuth($auth)
{
$this->auth = $auth;
}
// + all setters and getters...
}
型号:UserAuth.php
<?php
/**
* @Entity @Table(name="user_auth")
**/
class UserAuth
{
/** @Id @Column(type="integer") @GeneratedValue **/
protected $id;
/** @Column(type="integer") **/
protected $user_id;
/** @Column(type="string") **/
protected $username;
/** @Column(type="string") **/
protected $password;
/** @Column(type="string") **/
protected $role;
/**
* @OneToOne(targetEntity="User", inversedBy="auth")
* @JoinColumn(name="user_id", referencedColumnName="id")
*/
protected $user;
public function getUser()
{
return $this->user;
}
// + all setters and getters...
}
检索数据并更新它们没问题:
$user = $orm->find('User', 2);
echo $user->getAuth()->getUsername();
$user->getAuth()->setUsername('jprlauzier');
$orm->persist($user);
$orm->flush();
但是,不可能创建一个新的:
$user = $orm->find('User', 3);
$auth = new UserAuth();
$auth->setUsername('newusername');
$auth->setPassword('51abb9636078defbf888d8457a7c76f85c8f114c');
$auth->setRole('user');
$orm->persist($auth);
$user->setAuth($auth);
$orm->persist($user);
$orm->flush();
错误:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null' in /Applications/MAMP/htdocs/test/library/Doctrine/DBAL/Statement.php:131 Stack trace: #0 /Applications/MAMP/htdocs/test/library/Doctrine/DBAL/Statement.php(131): PDOStatement- >execute(NULL) #1 /Applications/MAMP/htdocs/test/library/Doctrine/ORM/Persisters/BasicEntityPersister.php(239): Doctrine\DBAL\Statement->execute() #2 /Applications/MAMP/htdocs/test/library/Doctrine/ORM/UnitOfWork.php(870): Doctrine\ORM\Persisters\BasicEntityPersister->executeInserts() #3 /Applications/MAMP/htdocs/test/library/Doctrine/ORM/UnitOfWork.php(304): Doctrine\ORM\UnitOfWork->executeInserts(Object(Doctrine\ORM\Mapping\ClassMetadata)) #4 /Applications/MAMP/htdocs/test/library/Doctrine/ORM/EntityManager.php(355): Doctrine\ORM\UnitOfWork->commit(NULL) #5 /Applications/MAMP/htdocs/test/application/Bootstrap.php(106): Doctrine\ORM\EntityManager->flush() #6 /Applications/MAMP/htdocs/test/application/Bo in /Applications/MAMP/htdocs/test/library/Doctrine/DBAL/Statement.php on line 131
Doctrine 没有找到 user_id 在表 user_auth 中创建新条目。但是,我在我的模型中指出了 @JoinColumn(name="user_id", referencedColumnName="id") ......为了您的帮助!我整天都在寻找这个。