【问题标题】:Doctrine - OneToOne relation - EntityNotFoundException教义 - OneToOne 关系 - EntityNotFoundException
【发布时间】:2014-11-15 19:44:18
【问题描述】:

我想指定两个实体 Item 和 ItemPrice 之间的关系。 item 可以有价格,但不是必须的,所以应该是 sql 中的 left join 之类的东西。我使用 OneToOne 关系,JoinColumn 和 nullable=true,我得到 EntityNotFoundException 异常。这是我的代码:

class Item
{

/**
 * @ORM\Column(type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="IDENTITY")
 */
protected $item_id;

/**
 * @ORM\Column(type="string")
 */
protected $name;

/**
 * @ORM\Column(type="string")
 */
protected $image_file;

/**
 * @ORM\OneToOne(targetEntity="ItemPrice")
 * @ORM\JoinColumn(name="item_id", referencedColumnName="item_id", nullable=true)
 */
protected $price;
...
}


class ItemPrice
{

/**
 * @ORM\Column(type="integer")
 * @ORM\Id
 */
protected $item_id;

/**
 * @ORM\Column(type="integer")
 */
protected $gold;

/**
 * @ORM\Column(type="integer")
 */
protected $silver;

/**
 * @ORM\Column(type="integer")
 */
protected $bronze;
...
}

表格:

CREATE TABLE `item` (
`item_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(150) NOT NULL,
`image_file` varchar(100) DEFAULT NULL,
PRIMARY KEY (`item_id`),
UNIQUE KEY `uk_item_name` (`name`));

CREATE TABLE `item_price` (
`item_id` int(11) NOT NULL,
`gold` int(11) NOT NULL DEFAULT '0',
`silver` int(11) NOT NULL DEFAULT '0',
`bronze` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`item_id`));

我认为我所做的称为单向 OneToOne: http://doctrine-orm.readthedocs.org/en/latest/reference/association-mapping.html#one-to-one-unidirectional 在我看来,这正是我所需要的。

【问题讨论】:

  • 你能提供你的命名空间定义吗?
  • 我的回答能成功解决您的问题吗?

标签: php doctrine-orm zend-framework2


【解决方案1】:

我认为你的映射是错误的。

您在与ItemPrice 关联的OneToOne 关联中为item_id 加入列写nullable=true。这意味着如果 item_idnull 则没有关联的 ItemPrice。但是item_id 是主要的 id 列,因此总是有一个值,因此 ORM 将始终尝试为您的 Item 找到一个 ItemPrice,从而导致 EntityNotFoundException 您应该将ItemPrice 设为关系的拥有方,或者您应该在ItemPrice 中创建price_id 并将其用作连接列。

您应该考虑使用 Doctrine 来创建/插入您的表并验证您的实体定义,那么您就不会遇到这类问题。

【讨论】:

    猜你喜欢
    • 2018-10-01
    • 1970-01-01
    • 2019-01-24
    • 2014-10-15
    • 2011-04-08
    • 1970-01-01
    • 2021-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多