我有3张桌子: users,users_profile和extra table users_addresses。
用户类:
class User
{
/**
* @ORM\Id()
* @ORM\Column(name="user_id", type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
* @var int
*/
private $userId;
/**
* @ORM\OneToOne(targetEntity="Entity\UserProfile", cascade={"persist", "remove"}, mappedBy="user", fetch="LAZY")
* @var Entity\UserProfile
*/
private $profile;
/**
* @param Entity\UserProfile $profile
*/
public function setProfile(UserProfile $profile) {
$this->profile = $profile;
$profile->setUser($this);
return $this;
}
(...)
}
用户个人资料类
class UserProfile
{
/**
* @ORM\Id()
* @ORM\Column(name="profile_id", type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
* @var int
*/
private $profileId;
/**
* @ORM\OneToOne(targetEntity="Entity\User", inversedBy="profile")
* @ORM\JoinColumn(name="user_id", referencedColumnName="user_id")
* @var Entity\User
*/
private $user;
/**
* @ORM\ManyToMany(targetEntity="Entity\Address", cascade={"persist"})
* @ORM\JoinTable(name="users_addresses",
* joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="user_id")},
* inverseJoinColumns={@ORM\JoinColumn(name="address_id", referencedColumnName="address_id")}
* )
**/
private $addresses;
/**
* @param Address $address
*/
public function addAddress(Address $address) {
if (!$this->addresses->contains($address)) {
$this->addresses->add($address);
}
return $this;
}
(...)
}
地址类
class Address
{
/**
* @ORM\Id()
* @ORM\Column(name="address_id", type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
* @var int
*/
private $addressId;
/**
* @ORM\Column(type="string", length=128, nullable=false)
* @var string
*/
private $city;
(...)
}
为用户添加个人资料数据和地址
$userAddress = new \Entity\Address();
$userAddress->setStreet($street);
$userAddress->setCity($city);
$userAddress->setCountry($country);
$userAddress->setState($state);
$userAddress->setZipCode($zipCode);
$userProfile = new \Entity\UserProfile();
$userProfile->addAddress($userAddress);
$user = new \Entity\User();
$user->setProfile($userProfile);
$em->persist($user);
$em->flush();
我目前遇到的问题是实体仍然存在,但是' user_id'在联接表中(' users_addresses')不正确(' user_id' = 0,' address_id' =正确)。表'地址'不得包含额外字段,例如' user_id'。我做错了什么?
我需要这样的结构:
答案 0 :(得分:0)
您的建模显示表users
和users_profile
共享相同的主键,即user_id
,因此该列也是users
中users_profile
的外键1}}。
因此,您应该通过profile_id
替换Php注释中的user_id
,删除密钥自动生成指令,并更新(或删除并重新创建)架构。
class UserProfile {
/**
* @ORM\Id
* @ORM\Column(name="user_id", type="integer")
* @var int
*/
private $profileId;
/* ... */
}
然后
$ doctrine orm:info --verbose
Found 3 mapped entities:
[OK] Address
[OK] User
[OK] UserProfile
$ doctrine orm:schema-tool:create
ATTENTION: This operation should not be executed in a production environmnent.
Creating database schema...
Database schema created successfully!
如果您已有架构,请使用update
命令。
您还可以重命名php类属性($profileId
),以获得与DB模型的“一致性”,但我认为这并不重要,除非您拥有依赖于特定名称的代码。 / p>