【发布时间】:2019-01-07 09:24:01
【问题描述】:
动物:
| 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 |
我想做的是为dog 获取categories:
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();
}
}
【问题讨论】:
-
可以添加实体表名吗?
-
@hoover_D 抱歉,
Animals是实体名称 -
您必须被放置在 Animals 存储库中才能获取它们或进行加入..
-
@hoover_D 是的,抱歉,我的问题有误。现在是正确的
-
你能发布你的Entity Animals.php吗?
标签: php symfony doctrine entity arraycollection