首页 > 解决方案 > 如何从 ArrayCollection (Symfony) 中检索数据?

问题描述

动物:

| id | name |
|----|------|
| 1  | cat  |
| 2  | dog  |
| 3  | frog |

类别:

| id | name   |
|----|--------|
| 1  | green  |
| 2  | blue   |
| 3  | orange |

动物_类别:

| animals_id | category_id |
|------------|-------------|
| 1          | 1           |
| 2          | 1           |
| 2          | 2           |

我想要做的是获得categoriesfor dog

green, blue

这是我的方法:

控制器:

$id = '2';

$result = $this->getDoctrine()->getRepository('Animals:Category')->findByIdJoinedToCategory(['id'=>$id]);

动物资料库:

   public function findByIdJoinedToCategory()
    {
        $query = $this->getEntityManager()
            ->createQuery(
                'SELECT a, b FROM Animals:Category a
                JOIN a.category b');
        try {
            return $query->getResult();
        } catch (\Doctrine\ORM\NoResultException $e) {
            return null;
        }
    }

但我收到一条错误消息:

未知实体命名空间别名“动物”。

实体Animals

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
* @ORM\Entity(repositoryClass="App\Repository\AnimalsRepository")
*/
class Animals
{
  /**
  * @ORM\Id()
  * @ORM\GeneratedValue()
  * @ORM\Column(type="integer")
  */
  private $id;


  /**
  * @ORM\Column(type="string", length=255)
  */

  private $name;


  /**
  * @ORM\ManyToMany(targetEntity="Category")
  * @ORM\JoinColumn(name="category", referencedColumnName="id")
  */
  private $category;




  public function getId(): ?int
  {
    return $this->id;
  }


  public function getName()
  {
    return $this->name;
  }

  public function setName($name)
  {
    $this->name = $name;
  }


  public function getCategory()
  {
    return $this->category;
  }

  public function setCategory($category): self
  {
    $this->category = $category;

    return $this;
  }

  public function addCategory(Category $category): self
  {
    $this->category[] = $category;

    return $this;
  }

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

标签: phpsymfonydoctrineentityarraycollection

解决方案


没有Animals:Category实体。您有实体AnimalsCategory.

正确答案取决于您使用的是 Symfony 3 还是 4,因为 Symfony 3 使用实体别名(使用:您尝试使用的符号的命名空间),而 Symfony 4 更喜欢完全限定的命名空间(\App\Entity\Animals)。

因此,第一个错误是您尝试获取存储库的位置:

getRepository('Animals:Category')

findByIdJoinedToCategory()DQL 查询中的第二个:

'SELECT a, b FROM Animals:Category a
JOIN a.category b'

现在解决方案:

Symfony 3

因为看起来你没有任何捆绑包(我猜它是 Symfony 4 但无论如何),你没有任何实体命名空间别名,所以你应该简单地使用它的名字。

getRepository('Animals')

现在,我假设a你想引用Animals实体/表,所以它应该是

'SELECT a, b FROM Animals a
JOIN a.category b'

Symfony 4

如果你使用 Symfony 4,那么使用应该使用实体 FQNS 作为实体名称 ( App\Entity\Animals)。

所以它会是

getRepository('\App\Entity\Animals')

或者

getRepository(\App\Entity\Animals::class)

获取存储库。第二个更好,因为它会在需要时更容易重构(IDE 将能够找到类的用法)。

在查询中它会是

'SELECT a, b FROM App\Entity\Animals a
JOIN a.category b'

或者如果您想避免使用硬编码的字符串类名:

'SELECT a, b FROM ' . \App\Entity\Animals:class . ' a
JOIN a.category b'

推荐阅读