animals:
| id | name |
|----|------|
| 1 | cat |
| 2 | dog |
| 3 | frog |
category:
| id | name |
|----|--------|
| 1 | green |
| 2 | blue |
| 3 | orange |
animals_category:
| animals_id | category_id |
|------------|-------------|
| 1 | 1 |
| 2 | 1 |
| 2 | 2 |
What I want to do is get the categories
for dog
:
green, blue
This is my approach:
Controller:
$id = '2';
$result = $this->getDoctrine()->getRepository('Animals:Category')->findByIdJoinedToCategory(['id'=>$id]);
Animals Repository:
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;
}
}
But I get an error message:
Unknown Entity namespace alias 'Animals'.
entity 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();
}
}