0

我有两个实体RentalItem. Items 通过包含一些元数据的连接表与 s 相关联Rental,因此连接表实际上成为了第三个实体RentedItem

因为 aRentedItem可以通过其关联的Rentaland来识别Item,所以它不需要自己的 ID,而是使用由这两个外键组成的复合键作为主键。

/**
 * @ORM\Entity
 */
class Rental
{
    // ...
    /**
     * @ORM\OneToMany(targetEntity="RentedItem", mappedBy="rental", cascade={"all"})
     * @var ArrayCollection $rented_items
     */
    protected $rented_items;
    // ...
}

/**
 * @ORM\Entity
 */
class Item
{
    // ...
    // Note: The Item has no notion of any references to it.
}

/**
 * @ORM\Entity
 */
class RentedItem
{
    // ...
    /**
     * @ORM\Id
     * @ORM\ManyToOne(targetEntity="Rental", inversedBy="rented_items")
     * @var Rental $rental
     */
    protected $rental;
    /**
     * @ORM\Id
     * @ORM\ManyToOne(targetEntity="Item")
     * @var Item $item
     */
    protected $item;
    /**
     * @ORM\Column(type="boolean")
     * @var bool $is_returned
     */
    protected $is_returned = false;
    // ...
}

Rental可以通过 RESTful API 创建或更改A ,包括它的一些相关对象。相应的控制器使用DoctrineObjectZF2 DoctrineModule 的 hydrator 使用给定的表单数据对出租对象进行水合。新数据作为表单数组传递给 hydrator

$data = [
    // We only use the customer's ID to create a reference to an
    // existing customer. Altering or creating a customer via the
    // RestfulRentalController is not possible
    'customer' => 1, 
    'from_date' => '2016-03-09',
    'to_date' => '2016-03-22',
    // Rented items however should be alterable via the RestfulRentalController,
    // because they don't have their own API. Therefore we pass
    // the complete array representation to the hydrator
    'rented_items' => [
        [
            // Again, just as we did with the customer, 
            // only use the referenced item's ID, so that
            // changing an item is not possible
            'item' => 6, 
            'is_returned' => false
            // NOTE: obviously, the full array representation of
            // a rented item would also contain the 'rental' reference,
            // but since this is a new rental, there is no id yet, and
            // the reference should be implicitly clear via the array hirarchy
        ],
        [
            'item' => 42,
            'is_returned' => false
        ]
    ]
];

通常,水合器会正确设置引用,即使对于全新的实体和新关系也是如此。然而,由于这种复杂的关联,水合作用Rental失败了。编码

$hydrator = new \DoctrineModule\Stdlib\Hydrator\DoctrineObject($entity_manager);
$rental = $hydrator->hydrate($data, $rental);

失败,但出现以下异常

Doctrine\ORM\ORMException

File:

    /vagrant/app/vendor/doctrine/orm/lib/Doctrine/ORM/ORMException.php:294

Message:

    The identifier rental is missing for a query of Entity\RentedItem

我是否必须手动设置租用物品的参考资料?或者这可能是由错误的配置或其他原因引起的?

4

0 回答 0