Doctrine2 OneToOne映射中给出的ID错误

时间:2016-04-18 18:12:33

标签: mysql symfony doctrine-orm one-to-one

我现在认真堆叠了OneToOne映射时遇到的问题。

所以让我展示一下我现在拥有的东西:

OrderItem实体

/**
 * OrderItem
 *
 * @ORM\Table(name="order_item")
 * @ORM\Entity
 */
class OrderItem
{
    /**
     * @var integer
     *
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    // ... //

    /**
     * @ORM\OneToOne(targetEntity="UserPricingOption", mappedBy="orderItem")
     */
    private $userPricingOption;

    /**
     * @ORM\ManyToOne(targetEntity="Order", inversedBy="items")
     * @ORM\JoinColumn(referencedColumnName="id")
     */
    private $order;

    // ... //

UserPricingOption实体

/**
 * UserPricingOption
 *
 * @ORM\Table(name="user_pricing_option")
 * @ORM\Entity
 * @ExclusionPolicy("all")
 */
class UserPricingOption
{
    /**
     * @var integer
     *
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    // ... //

    /**
     * @ORM\OneToOne(targetEntity="OrderItem", inversedBy="userPricingOption")
     * @ORM\JoinColumn(referencedColumnName="id")
     */
    private $orderItem;

    // ... //

所以生成的表看起来像这样:

order_item

 * `id` 5

user_pricing_option

 * `id` 12
 * `order_item_id` 5

所以现在我正在努力做到以下几点:

echo $orderItem->getId(); // gives 5, `GOOD`
echo $orderItem->getUserPricingOption()->getId(); // gives 5 `BAD` (completely different user_pricing_option row),  it should return 12.

我真的不知道为什么会这样,请找到原始的Doctrine查询: 请记住,查询包含的信息比上面显示的示例更多

SELECT t0.id AS id_1, t0.guid AS guid_2, t0.created_at AS created_at_3, t0.modified_at AS modified_at_4, t5.id AS id_6, t5.guid AS guid_7, t5.created_at AS created_at_8, t5.modified_at AS modified_at_9, t5.user_id AS user_id_10, t5.order_item_id AS order_item_id_11, t5.pricing_option_id AS pricing_option_id_12, t13.id AS id_14, t13.guid AS guid_15, t13.created_at AS created_at_16, t13.modified_at AS modified_at_17, t13.user_id AS user_id_18, t13.order_item_id AS order_item_id_19, t13.product_variant_id AS product_variant_id_20, t0.order_invoice_id AS order_invoice_id_21, t0.order_id AS order_id_22 FROM order_item t0 LEFT JOIN user_pricing_option t5 ON t5.order_item_id = t0.id LEFT JOIN user_product_variant t13 ON t13.order_item_id = t0.id WHERE t0.order_id = ? [131]

所以基本上$orderItem->getUserPricingOption()->getId()始终返回与$orderItem->getId();

相同的ID

任何人都可能看到发生了什么?

1 个答案:

答案 0 :(得分:0)

OneToOne bidireccional? 尝试在joinColumn中定义带有引用id的列的名称。

/**
     * @ORM\OneToOne(targetEntity="OrderItem", inversedBy="userPricingOption")
     * @ORM\JoinColumn(name="order_item_id", referencedColumnName="id")
     */
    private $orderItem;

http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/association-mapping.html#one-to-one-bidirectional