2

考虑一个具有外键的实体。我们收到一个包含整数形式的外键的数组,我们想从数组中填充当前实体(这可以是更新或创建,没有区别)。到目前为止,我一直无法在文档中找到如何以“symfony2/doctrine”方式执行此更新的示例。

如果我们将私有变量的类型更改为整数而不是外部实体类型的对象,我们将丢失 ORM 映射/自动实例化/等。如果我们保持原样,我们不能用一个简单的整数来设置它。

原则文档规定我们不应从实体内部访问实体管理器(目的是在设置当前实体值之前从键中“查找”外部实体),无论如何我还没有找到有关如何执行此操作的文档想要。最佳实践要求从数组中填充对象应该作为该对象上的对象方法发生。常识表明应该支持一个简单的数组,并且不应该要求最终用户/控制器知道创建外部实体。

有人可以指出我理智的方向吗?

示例代码:

<?php
namespace Prefix\MyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
class Item
{
    private $itemid;

    /*
             * --- omitted for brevity ---
             */
    private $categoryid;
    public function getItemid()
    {
        return $this->itemid;
    }
    /**
     * --- omitted for brevity again ---
     */
    public function setCategoryid(\Prefix\MyBundle\Entity\Category $categoryid = null)
    {
        $this->categoryid = $categoryid;

        return $this;
    }
    public function getCategoryid()
    {
        return $this->categoryid;
    }
    public function fromArray($data = array())
    {
        $updated = false;
        if ( isset($data['Category']) )
        {
            /* We know that $data['Category'] will be an int */
            $this->setCategoryid($data['Category']); //Fails invalid type!
            $updated = true;
        }
        return $updated;
    }
}
4

2 回答 2

0

So, you have to create your Category Object (owning side, many side), then fetch every Item object from db (you have an array of integer that are IDs, so you can do something like ->findById() or a custom DQL query where you can fetch them into a shot). Subsequently you have to call, for every fetched object, a ->setItems() or ->addItem() and use ->persist(); ->flush(); of entity manager.

于 2013-06-17T12:46:29.033 回答
-1

当您使用教义时,您不应该使用外键(而是使用类别对象。所以实际上您应该在函数之外将 id 转换为类别。

Another option is to add a new column called category which is of type integer and you set that directly so that you know have 2 class variables pointing to the same object but one has the relation the other just the id

/**
 * @ManyToOne...
 */
protected $category;
/**
 * @Column(type="integer")
 */
protected $categoryid;

public function setCategory(\Prefix\MyBundle\Entity\Category $category = null)
{
    $this->category = $category;

    return $this;
 }
public function getCategory()
{
    return $this->category;
}
public function setCategoryId($categoryid = null)
{
    $this->categoryid = $categoryid;

    return $this;
 }
public function getCategoryId()
{
    return $this->categoryid;
}
于 2013-06-14T23:19:49.587 回答