【问题标题】:Doctrine 2, error inserting in table with foreign key教义 2,使用外键在表中插入错误
【发布时间】:2013-11-17 11:27:00
【问题描述】:

我是 Doctrine 的新手,是我使用它的第一个项目,我在尝试插入新用户时遇到错误。

问题是我有一个带有外键 Country 的类 User,当我尝试插入用户 Doctrine 时也尝试插入国家/地区,该国家/地区已经存在,因此 PDO 启动违反完整性约束和 Doctrine a Doctrine\ DBAL\DBALException。

我知道注释 cascade={"persist"} 使国家实体写入数据库,没有它,学说会引发另一个错误:

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;

        }

任何线索将不胜感激。 谢谢。

【问题讨论】:

  • 可能没有定义表别名。
  • 如果表别名是这样的:@Table(name="country"),那么就定义了...

标签: php mysql doctrine-orm


【解决方案1】:

把 cascade=persist 放回去。

您需要检查数据库以查看该国家/地区是否存在。您插入现有国家/地区失败,因为国家/地区对象需要由实体管理器管理。

$country = $countryRepository->find($countryId);
if (!$country) 
{
    $country = new Country();
    $entityManager->persist($country);
}
$user->setCountry($country);

【讨论】:

  • 谢谢!我最终将国家类型更改为整数并删除所有关系,您的方式更简单更好,再次感谢。
猜你喜欢
  • 2015-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-13
  • 1970-01-01
  • 1970-01-01
  • 2012-12-05
  • 1970-01-01
相关资源
最近更新 更多