我是使用Doctrine的新手,是我使用它的第一个项目,当我尝试插入新用户时遇到错误。
问题是我有一个带有外键国家的类用户,当我尝试插入用户学说时,也尝试插入国家/地区,该国家/地区已经存在,因此 PDO 启动完整性约束违规和学说 A 学说''DBAL''DBALException。
我知道注释级联={"持久"}使国家实体要写在数据库中,没有它,学说会启动另一个错误:
A new entity was found through the relationship 'User#country' that was not configured to cascade persist operations for entity: Country@0000000078b1861f00007f935266d9fe. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist this association in the mapping for example @ManyToOne(..,cascade={"persist"}). If you cannot find out which entity causes the problem implement 'Country#__toString()' to get a clue.
我已经尝试了所有级联选项,只有坚持,上面的所有错误都没有出现......
是否有类似 cascade={"no-persist"} 的东西,或者告诉教义此属性的值必须已经插入到表国家/地区???
一些代码:
/**
* User
*
* @Table(name="user")
* @Entity
*/
class User {
...
/**
* @var Country
*
* @OneToOne(targetEntity="Country", cascade={"persist"})
* @JoinColumn(name="country", referencedColumnName="id")
*/
private $country
...
}
/**
* Country
*
* @Table(name="country")
* @Entity
*/
class Country {
...
/**
* @var integer
*
* @Column(name="id", type="integer")
* @Id
*/
private $id;
}
任何线索将不胜感激。谢谢。
把级联=持久放回去。
您需要检查数据库以查看该国家/地区是否存在。 插入现有国家/地区失败,因为国家/地区对象需要由实体管理器管理。
$country = $countryRepository->find($countryId);
if (!$country)
{
$country = new Country();
$entityManager->persist($country);
}
$user->setCountry($country);