【问题标题】:This is a Doctrine 2.2 Foreign Key Bug?这是 Doctrine 2.2 外键错误?
【发布时间】:2012-05-07 03:44:29
【问题描述】:

我的代码:

        $item = new Entity\Item();

        $item->setAccountId($account["id"]);
        $item->setCategory((string)$data->category);
        $item->setRegion((string)$data->region);
        $item->setFlag(0);
        $item->setRank(0);
        $item->setPhone("");
        $item->setEmail("");
        $item->setURL((string)$data->url);
        $item->setTags($tags);

        //var_dump($item);
        //die();

        $this->em->persist($item);
        $this->em->flush();
        $this->em->clear();

注解关系:

/////////////////////////////////////////////////////////////////////////
// Relations                                                     //
/////////////////////////////////////////////////////////////////////////

/**
* @ManyToOne(targetEntity="Account", inversedBy="items")
* @JoinColumn(name="account_id", referencedColumnName="id")
*/
private $account;

/////////////////////////////////////////////////////////////////////////
// ForeingKey                                                           //
/////////////////////////////////////////////////////////////////////////

/**
 * @Column(type="integer")
 */
protected $account_id;   

如果我使用旧的学说 (2.0) 代码工作,如果我设置为 2.2 ,代码会抛出这个异常:

SQLSTATE[23000]:违反完整性约束:1048 列 'account_id' 不能为空

在 2.2 中我需要使用 Parent 实体来插入 Child 实体吗?

【问题讨论】:

  • 你确定$account["id"] 不为空吗?

标签: php foreign-keys doctrine-orm


【解决方案1】:

从 Doctrine2 的角度来看,您的对象应该形成一个对象图,其中外键没有位置。正因为如此,我觉得你真的很奇怪

  • 有一个作为外键的 attribute_id 属性
  • 说它在 2.0 中工作

我不确定它在 2.0 中的情况如何,但我不记得属性中有相关对象的 ID。

因此,您应该删除 $account_id 属性,并使用 $item->setAccount($account),其中 $account 是 Account 类的对象,以便 Doctrine 正确处理关系。

您也可以尝试让 Doctrine 使用以下命令为您生成实体骨架:

php doctrine.php orm:generate-entities /tmp/entites

然后检查 /tmp/entities 中生成的文件,你会看到应该是什么样子。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-22
    • 1970-01-01
    • 2017-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-07
    相关资源
    最近更新 更多