【发布时间】:2020-01-18 22:52:39
【问题描述】:
我的项目中有两个使用 Doctrine 的实体:
class User
{
/**
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
* @ORM\Column(type="integer")
*/
private $user_id;
/**
* @ORM\Column(type="string")
*/
private $username;
/**
* @ORM\Column(type="string")
*/
private $password;
/**
* @ORM\OneToOne(targetEntity="UserProfile", cascade={"persist", "remove"})
* @ORM\JoinColumn(name="user_id", referencedColumnName="user_id", unique=true)
* @var UserProfile
*/
private $profile;
//...
}
class UserProfile
{
/**
* @ORM\Id
* @ORM\OneToOne(targetEntity="User")
* @ORM\JoinColumn(name="user_id", referencedColumnName="user_id")
*/
private $user;
/**
* @ORM\Id
* @ORM\Column(type="integer")
*/
private $user_id;
/**
* @ORM\Column(type="string")
*/
private $first_name = '';
/**
* @ORM\Column(type="string")
*/
private $last_name = '';
//...
}
我正在尝试使用以下方法在数据库中生成新行:
$user = new User();
$user->setUsername('test');
$user->setEmail('test@example.com');
$user->setPassword(password_hash('password', PASSWORD_BCRYPT));
$em->persist($user);
$em->flush();
$userProfile = new UserProfile();
$userProfile->setFirstName('test');
$userProfile->setLastName('user');
$user->setProfile($userProfile);
$em->persist($user);
$em->flush();
这会引发错误:
致命错误:未捕获的 Doctrine\ORM\ORMException: Entity of type App\Entity\UserProfile 缺少为字段“用户”分配的 ID。这 此实体的标识符生成策略需要 ID 字段 在调用 EntityManager#persist() 之前填充。如果你想 自动生成的标识符,而不是您需要调整 相应的元数据映射。在 /home/site/vendor/doctrine/orm/lib/Doctrine/ORM/ORMException.php on 第 87 行
如果我添加一个没有 UserProfile 的用户,这工作正常,我会在数据库中获得一行,其中 user_id 是从 MySQL 自动增量生成的。创建新配置文件时如何让 UserProfile 使用新创建的 user_id?
我是不是把关联的事情复杂化了?我应该只在 UserProfile 上创建一个 setUserId() 方法吗?
【问题讨论】:
-
你能把
User::setProfile()函数的代码贴出来吗? -
没什么特别的:
public function setProfile(UserProfile $profile) : self { $this->profile = $profile; return $this; }
标签: php doctrine-orm