1

Есть сущность "Организации" и сущность "Руководители организаций". При добавлении организации нужно одновременно добавлять руководителя, в одной форме или другим способом. Руководитель связан с организацией по id. Как это сделать в лучших практиках?

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Table(name="organization")
 * @ORM\Entity
 */
class Organization
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */ 
    private $id;

    /**
     * @ORM\Column(type="string")
     * @Assert\NotBlank()
     */       
    private $name;

    /**
     * @ORM\Column(type="string")
     * @Assert\NotBlank()
     */       
    private $ur_address;

    /**
     * @ORM\OneToMany(
     *      targetEntity="Rukovoditel",
     *      mappedBy="id_organization",
     *      orphanRemoval=true
     * )
     */
    private $rukovoditel;     

    /**
     * Set name
     *
     * @param string $name
     *
     * @return Organization
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Add rukovoditel
     *
     * @param \AppBundle\Entity\Rukovoditel $rukovoditel
     *
     * @return Organization
     */
    public function addRukovoditel(\AppBundle\Entity\Rukovoditel $rukovoditel)
    {
        $this->rukovoditel[] = $rukovoditel;

        return $this;
    }

    /**
     * Remove rukovoditel
     *
     * @param \AppBundle\Entity\Rukovoditel $rukovoditel
     */
    public function removeRukovoditel(\AppBundle\Entity\Rukovoditel $rukovoditel)
    {
        $this->rukovoditel->removeElement($rukovoditel);
    }

    /**
     * Get rukovoditel
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getRukovoditel()
    {
        return $this->rukovoditel;
    }

    /**
     * Set urAddress
     *
     * @param string $urAddress
     *
     * @return Organization
     */
    public function setUrAddress($urAddress)
    {
        $this->ur_address = $urAddress;

        return $this;
    }

    /**
     * Get urAddress
     *
     * @return string
     */
    public function getUrAddress()
    {
        return $this->ur_address;
    }
}







<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Table(name="rukovoditel")
 * @ORM\Entity
 */
class Rukovoditel
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */         
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="Organization")
     * @ORM\JoinColumn(nullable=false)
     */        
    private $id_organization;

    /**
     * @ORM\Column(type="string")
     * @Assert\NotBlank()
     */       
    private $fio;

    /**
     * @ORM\Column(type="string")
     * @Assert\NotBlank()
     */       
    private $zvanie;

    /**
     * @ORM\OneToMany(
     *      targetEntity="RukovoditelZamestitel",
     *      mappedBy="id_rukovoditel",
     *      orphanRemoval=true
     * )
     */
    private $rukovoditel_zamestitel;     
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->rukovoditel_zamestitel = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set fio
     *
     * @param string $fio
     *
     * @return Rukovoditel
     */
    public function setFio($fio)
    {
        $this->fio = $fio;

        return $this;
    }

    /**
     * Get fio
     *
     * @return string
     */
    public function getFio()
    {
        return $this->fio;
    }

    /**
     * Set zvanie
     *
     * @param string $zvanie
     *
     * @return Rukovoditel
     */
    public function setZvanie($zvanie)
    {
        $this->zvanie = $zvanie;

        return $this;
    }

    /**
     * Get zvanie
     *
     * @return string
     */
    public function getZvanie()
    {
        return $this->zvanie;
    }

    /**
     * Set idOrganization
     *
     * @param \AppBundle\Entity\Organization $idOrganization
     *
     * @return Rukovoditel
     */
    public function setIdOrganization(\AppBundle\Entity\Organization $idOrganization)
    {
        $this->id_organization = $idOrganization;

        return $this;
    }

    /**
     * Get idOrganization
     *
     * @return \AppBundle\Entity\Organization
     */
    public function getIdOrganization()
    {
        return $this->id_organization;
    }

    /**
     * Add rukovoditelZamestitel
     *
     * @param \AppBundle\Entity\RukovoditelZamestitel $rukovoditelZamestitel
     *
     * @return Rukovoditel
     */
    public function addRukovoditelZamestitel(\AppBundle\Entity\RukovoditelZamestitel $rukovoditelZamestitel)
    {
        $this->rukovoditel_zamestitel[] = $rukovoditelZamestitel;

        return $this;
    }

    /**
     * Remove rukovoditelZamestitel
     *
     * @param \AppBundle\Entity\RukovoditelZamestitel $rukovoditelZamestitel
     */
    public function removeRukovoditelZamestitel(\AppBundle\Entity\RukovoditelZamestitel $rukovoditelZamestitel)
    {
        $this->rukovoditel_zamestitel->removeElement($rukovoditelZamestitel);
    }

    /**
     * Get rukovoditelZamestitel
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getRukovoditelZamestitel()
    {
        return $this->rukovoditel_zamestitel;
    }
}
2
  • У Вас в проекте в папке Entity должен быть файл сущности таблицы, которая отвечает за организации. Запостите сюда содержимое этого файла, тогда станет понятнее как добавить руководителя. Ну и файл сущности руководителя тоже не забудьте показать. 4 янв 2016 в 19:21
  • Если вам дан исчерпывающий ответ, отметьте его как верный (галка напротив выбранного ответа). 5 янв 2016 в 0:40

1 ответ 1

1

Пишем примерно так (не ручаюсь за точность):

$rukovoditel = new Entity\Rukovoditel();
$rukovoditel->setFio('Иванов Иван Иванович')
$rukovoditel->setZvanie('Дежурный по стоянке торпедных катеров')
//задаем остальные свойства руководителя
$em->persist($rukovoditel);
$em->flush();

$organization = new Entity\Organization();
//задаем свойства организации
$organization->addRukovoditel($rukovoditel)
$em->persist($organization);
$em->flush();

Надеюсь ничего не напутал. С симфонией года два не работал.

4
  • Этот момент я понял. А как эти данные получить от пользователя? Как в билдере форм работать с несколькими сущностями и потом их обрабатывать в контроллере? Или нужно по-другому решать? 5 янв 2016 в 6:47
  • Сущность руководителя можно построить отдельно, а потом внедрить ее в сущность организации уже в контроллере. Но я уже не помню все нюансы работы с билдером. Возможно это делается как-то иначе. 5 янв 2016 в 10:19
  • пока смог получить остальные данные через параметры запроса - $request->request->get('test'), а дальше как вы писали выше. Как сделать по методологии symfony... 5 янв 2016 в 12:35
  • Я вот думаю... У меня в проектах на Symfony были сущности с множеством связей. Причем эти связи пронизывали все сущности вдоль и поперек. Если бы я пытался вот так выстроить формы по каким-то правилам, то запутался бы, да и не смог бы построить формы так, как мне хочется. Поэтому я все это всегда разделял. Но я видел где-то в примерах построение связанных форм. 5 янв 2016 в 12:47

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.