iKapex
@iKapex

Как вывести результаты из связанной таблицы?

У меня есть таблица:
/**
 * Fcsnotificationea
 *
 * @ORM\Table(name="fcsNotificationEA")
 * @ORM\Entity
 */
class Fcsnotificationea
{
...
    /**
     * @ORM\OneToMany(targetEntity="Attachmentstoea", mappedBy="Fcsnotificationea")
     **/
    private $attachments;
...
/**
     * Constructor
     */
    public function __construct()
    {
        $this->attachments = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add attachment
     *
     * @param \Custom\ScanFilesBundle\Entity\Attachmentstoea $attachment
     *
     * @return Fcsnotificationea
     */
    public function addAttachment(\Custom\ScanFilesBundle\Entity\Attachmentstoea $attachment)
    {
        $this->attachments[] = $attachment;

        return $this;
    }

    /**
     * Remove attachment
     *
     * @param \Custom\ScanFilesBundle\Entity\Attachmentstoea $attachment
     */
    public function removeAttachment(\Custom\ScanFilesBundle\Entity\Attachmentstoea $attachment)
    {
        $this->attachments->removeElement($attachment);
    }

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

и есть еще одна:

/**
 * Attachmentstoea
 *
 * @ORM\Table(name="attachmentsToEA", indexes={@ORM\Index(name="notificationEAid", columns={"notificationEAid", "id"}), @ORM\Index(name="IDX_5637D788CEB3C986", columns={"notificationEAid"})})
 * @ORM\Entity
 */
class Attachmentstoea
{
...
    /**
     * @var \Fcsnotificationea
     *
     * @ORM\ManyToOne(targetEntity="Fcsnotificationea")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="notificationEAid", referencedColumnName="id")
     * })
     */
    private $notificationeaid;
...

у меня сгенерены методы типа

/**
     * Add attachment
     *
     * @param \Custom\ScanFilesBundle\Entity\Attachmentstoea $attachment
     *
     * @return Fcsnotificationea
     */
    public function addAttachment(\Custom\ScanFilesBundle\Entity\Attachmentstoea $attachment)
    {
        $this->attachments[] = $attachment;

        return $this;
    }

сначала я делаю сеттеры для объекта Fcsnotificationea. Делаю persist для объекта Fcsnotificationea. Но flush не делаю.

Потом делаю сеттеры для объекта Attachmentstoea. И только потом вызываю сеттер для объекта Fcsnotificationea :
$eaNotification->addAttachment($eaAttachments);
и только потом делаю flush.

Вобщем-то база наполняется нормально.

но мне надо в twig выводить информацию и я никак не могу вызвать метод getAttachments для Fcsnotificationea. Хотя в entity этот метод есть:

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


пробую вызывать этот метод в twig'e
{% for notification in notificationsEA %}
  {% for attach in notification.getAttachments %}

мне пишут: Undefined index: Fcsnotificationea, где строка {% for attach in notification.getAttachments %}

по-разному пробовала делать select результата и с joinом и без join'a - безрезультатно. Никак не могу достучаться до attachemts:

Делаю так запрос вобщем:
$twig_params["notificationsEA"] = $em->createQueryBuilder()
                                           ->select('n')
                                           ->from('CustomScanFilesBundle:Fcsnotificationea', 'n')
                                           ->setFirstResult($page)
                                           ->setMaxResults(10)
                                           ->join('CustomScanFilesBundle:Attachmentstoea', 'a',
                                           \Doctrine\ORM\Query\Expr\Join::WITH, 'n.id = a.notificationeaid')
                                           ->getQuery()
                                           ->getResult();
  • Вопрос задан
  • 266 просмотров
Пригласить эксперта
Ответы на вопрос 1
Fesor
@Fesor
Full-stack developer (Symfony, Angular)
У меня есть таблица:

Не таблица, а сущность. Doctrine исповедует принцип persistence ignorance.

Зачем так сложно то? Настраиваем каскадный персист для связи и наш код упрощается до:

$notification = new FcsNotificationEA();
// добавляем 3 аттачмента
$notification->add(new Attachment());
$notification->add(new Attachment());
$notification->add(new Attachment());

$this->notificationsRepository->add($notification); // внутри add происходит persist

$this->get('doctrine.orm.entity_manager')->flush(); // коммитим изменения в базу

return $this->render('some_template.twig', compact('notification'));


p.s. все же подумайте о том что бы нормально именовать объекты... ибо не понятно что это такое.
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы