OneToMany或OneToOne,我走的是正确还是错误的道路?

时间:2014-09-07 17:44:57

标签: php symfony orm doctrine-orm mapping

我有这个数据库模型:  single database

然后我创建了这个实体(我只是离开了关系部分,因为另一个与主题无关):

Orders.php

class Orders {
    /**
     * @ORM\ManyToOne(targetEntity="Person", inversedBy="orders")
     * @ORM\JoinColumn(name="person_id", referencedColumnName="id")
     * */
    protected $person;

    public function setPerson(Person $person)
    {
        $this->person = $person;
        return $this;
    }

    public function getPerson()
    {
        return $this->person;
    }

}

Person.php

class Person {
    /**
     * @ORM\OneToMany(targetEntity="NaturalPerson", mappedBy="person")
     * */
    private $naturals;

    /**
     * @ORM\OneToMany(targetEntity="LegalPerson", mappedBy="person")
     * */
    private $legals;

    /**
     * @ORM\OneToMany(targetEntity="Orders", mappedBy="person")
     * */
    private $orders;

    public function __construct()
    {
        $this->naturals = new ArrayCollection();
        $this->legals = new ArrayCollection();
        $this->orders = new ArrayCollection();
    }

    public function getNaturals()
    {
        return $this->naturals;
    }

    public function getLegals()
    {
        return $this->legals;
    }

    public function getOrders()
    {
        return $this->orders;
    }

}

NaturalPerson.php

class NaturalPerson {

    /**
     * @ORM\Id
     * @ORM\ManyToOne(targetEntity="Person", inversedBy="naturals")
     * @ORM\JoinColumn(name="person_id", referencedColumnName="id")
     */
    protected $person;

    /**
     * @ORM\Column(name="identification_type", type="ci_type", nullable=false)
     * @DoctrineAssert\Enum(entity="Tanane\FrontendBundle\DBAL\Types\CIType")
     */
    protected $identification_type;

    /**
     * @ORM\Column(name="ci", type="integer", nullable=false)
     */
    protected $ci;

    public function setPerson(Person $person)
    {
        $this->person = $person;
        return $this;
    }

    public function getPerson()
    {
        return $this->person;
    }

    public function setIdentificationType($identification_type)
    {
        $this->identification_type = $identification_type;
        return $this;
    }

    public function getIdentificationType()
    {
        return $this->identification_type;
    }

    public function setCI($ci)
    {
        $this->ci = $ci;
        return $this;
    }

    public function getCI()
    {
        return $this->ci;
    }

}

我省略了LegalPerson,因为它与NaturalPerson几乎相同,所以这就是问题所在。映射看起来不错,但我如何从Orders获取相关记录?

这背后的想法是每个Orders我需要知道Person属于哪个(订单)以及存储在NaturalPersonLegalPerson的额外信息取决于person.type

请参阅此代码:

public function getOrdersAction()
{
    $response = array();
    $em = $this->getDoctrine()->getManager();

    $entities = $em->getRepository("FrontendBundle:Orders")->findAll();

    if (!$entities)
    {
        $response['message'] = "No se encontraron resultados";
    }

    $orders = array();
    foreach ($entities as $entity)
    {

        $personType = $entity->getPerson()->getPersonType();

        $order = array();
        $order[] = $entity->getNickname();

        // Here I'm trying to access to `Naturals` methods from `Orders` 
        if ($personType == 1)
        {
            $order[] = $entity->getPerson()->getNaturals()[0]->getIdentificationType() . $entity->getPerson()->getNaturals()[0]->getCI();
        }
        elseif ($personType == 2)
        {
            $order[] = $entity->getPerson()->getLegals()[0]->getIdentificationType() . $entity->getPerson()->getLegals()[0]->getRIF();
        }

        $orders[] = $order;
    }

    $response['data'] = $orders;
    return new JsonResponse($response);
}

但是我收到了这个错误:

  

错误:在a上调用成员函数getIdentificationType()   非对象   /var/www/html/tanane/src/Tanane/BackendBundle/Controller/OrderController.php   第115行

也许我的映射是错误的,因为我应该在OneToOnePerson之间NaturalPerson(这听起来像DER显示的逻辑错误)或者可能不是,但是我不知道我不知道如何只为一条记录获取相关属性,我阅读了文档here以及here,但他们没有谈论这部分,或者我没有看到它,有什么建议吗?想法?提示?

尝试使用存储库和DQL来解决问题

我正在Repository类中构建一个函数来获取数据而不是变得复杂,因为显然我的问题是,所以我这样做了:

public function getOrders($person_type = 1)
{
    $qb = $this->getEntityManager()->createQueryBuilder();

    $qb
            ->select('ord.*, ps.*')
            ->from("FrontendBundle:Orders", "ord")
            ->join('FrontendBUndle:Person', 'ps', 'WITH', 'ps.id = ord.person_id')
            ->orderBy('ord.created', 'DESC');

    if ($person_type == 1)
    {
        $qb
                ->select('np.*')
                ->join('FrontendBundle:NaturalPerson', 'np', 'WITH', 'ps.id = np.person'); // Join NaturalPerson table
    }
    elseif ($person_type == 2)
    {
        $qb
                ->select('lp.*')
                ->join('FrontendBundle:LegalPerson', 'lp', 'WITH', 'ps.id = lp.person'); // Join NaturalPerson table
    }

    return $qb->getQuery()->getResult();
}

我还没有测试,所以也许它不会工作,但是,如果想要获取两个表的额外信息,那么使用这个DQL,我做了我如何通过$person_type里面Person {1}}表?这有点复杂,至少对我而言

运行原始查询以查看列是否为NULL

我构建这个简单的查询只是为了测试结果是NULL

SELECT
    ord.id,
    ord.person_id as ord_person_id,
  ord.nickname,
  ps.id,
  ps.description,
  np.person_id as natural_person_id,
  np.identification_type,
    np.ci
FROM
    orders ord
LEFT JOIN person ps ON ord.person_id = ps.id
LEFT JOIN natural_person np ON np.person_id = ps.id
WHERE
    ps.person_type = 1;

这是什么查询返回:

enter image description here

因此

中没有NULL列

用于创建新订单的CRUD

// Set Person entity
$entityPerson = new Person();
$person_type === 1 ? $entityPerson->setDescription($orders['nat']['person']['description']) : $entityPerson->setDescription($orders['leg']['person']['description']);
$person_type === 1 ? $entityPerson->setContactPerson($orders['nat']['person']['contact_person']) : $entityPerson->setContactPerson($orders['leg']['person']['contact_person']);
$entityPerson->setPersonType($person_type);

$em->persist($entityPerson);
$em->flush();

...

if ($person_type === 1)
{
    // Set NaturalPerson entity
    $entityNatural = new NaturalPerson();
    $entityNatural->setIdentificationType($orders['nat']['identification_type']);
    $entityNatural->setCI($orders['nat']['ci']);

    $em->persist($entityNatural);
    $em->flush();
}
elseif ($person_type === 2)
{
    // Set LegalPerson entity
    $entityLegal = new LegalPerson();
    $entityLegal->setIdentificationType($orders['leg']['identification_type']);
    $entityLegal->setRIF($orders['leg']['rif']);

    $em->persist($entityLegal);
    $em->flush();
}

2 个答案:

答案 0 :(得分:1)

也许,其他问题。您可以忘记将NaturalPersonLegalPerson分配给Person实体。所以你需要在调用getIdentificationType()之前检查它:

if($personType == 1){
    if(null !== $natural = $entity->getPerson()->getNaturals()[0]){
       $order[] = $natural->getIdentificationType() . $natural->getCI();
    }
}elseif($personType == 2){
    if(null !== $legal = $entity->getPerson()->getLegals()[0]){
       $order[] = $legal->getIdentificationType() . $legal->getRIF();
    }
}

答案 1 :(得分:1)

由于LegalPersonNaturalPersonPerson的特化,我建议使用Doctrine所谓的类表继承(documentation)。

你会:

Person.php

/**
 * @ORM\Table(name="person")
 * @ORM\Entity
 * @ORM\InheritanceType("JOINED")
 * @ORM\DiscriminatorColumn(name="discr", type="string")
 * @ORM\DiscriminatorMap({
 *     "natural" = "NaturalPerson",
 *     "legal" = "LegalPerson",
 * })
 */
class Person {
    /**
     * @ORM\OneToMany(targetEntity="Orders", mappedBy="person")
     * */
    private $orders;

    public function __construct()
    {
        $this->orders = new ArrayCollection();
    }

    public function getOrders()
    {
        return $this->orders;
    }

}

NaturalPerson.php

/**
 * @ORM\Table(name="natural_person")
 * @ORM\Entity
 */
class NaturalPerson extends Person {
    /**
     * @ORM\Column(name="identification_type", type="ci_type", nullable=false)
     * @DoctrineAssert\Enum(entity="Tanane\FrontendBundle\DBAL\Types\CIType")
     */
    protected $identification_type;

    /**
     * @ORM\Column(name="ci", type="integer", nullable=false)
     */
    protected $ci;

    public function setIdentificationType($identification_type)
    {
        $this->identification_type = $identification_type;
        return $this;
    }

    public function getIdentificationType()
    {
        return $this->identification_type;
    }

    public function setCI($ci)
    {
        $this->ci = $ci;
        return $this;
    }

    public function getCI()
    {
        return $this->ci;
    }
}

Order.php保持不变。

如您所见,现在NaturalPersonLegalPerson都延伸Person。由于您已更改实体定义,因此必须更新数据库架构。

现在,在您的Controller中,您只需执行此操作:

foreach ($entities as $entity)
{
    $person = $entity->getPerson();

    $order = array();
    $order[] = $entity->getNickname();

    if ($person instanceof NaturalPerson)
    {
        $order[] = $person->getIdentificationType() . $person->getCI();
    }
    else // it has to be LegalPerson
    {
        $order[] = $person->getIdentificationType() . $person->getRIF();
    }

    $orders[] = $order;
}

不要忘记为use添加NaturalPerson语句!

这样您只能使用NaturalPersonLegalPerson的实例。我相信你可以进一步改善这一点。

最后,您必须为此更改CRUD。您不再直接使用Person(事实上,它应该是abstract),所以现在您需要分别处理NaturalPersonLegalPerson的CRUD。每个都有TypeController,视图等。

您的代码现在看起来像这样:

if ($person_type === 1)
{
    $entityPerson = new NaturalPerson();
    $entityPerson->setDescription($orders['nat']['person']['description']);
    $entityPerson->setContactPerson($orders['nat']['person']['contact_person']);
    $entityPerson->setIdentificationType($orders['nat']['identification_type']);
    $entityPerson->setCI($orders['nat']['ci']);

    $em->persist($entityPerson);
    $em->flush();
}
elseif ($person_type === 2)
{
    $entityPerson = new LegalPerson();
    $entityPerson->setDescription($orders['leg']['person']['description']);
    $entityPerson->setContactPerson($orders['leg']['person']['contact_person']);
    $entityPerson->setIdentificationType($orders['leg']['identification_type']);
    $entityPerson->setRIF($orders['leg']['rif']);

    $em->persist($entityPerson);
    $em->flush();
}