我正在建立一个网站,上面显示一些带有菜单的项目。在此菜单中,您可以选择一种语言来过滤项目。我的问题是查询以获取特定语言的项目。 我有2个实体,即Project和Language:
项目:
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="App\Repository\ProjectRepository")
*/
class Project
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\ManyToMany(targetEntity="App\Entity\Language", inversedBy="projects")
*/
private $languages;
public function __construct()
{
$this->languages = new ArrayCollection();
}
/**
* @return Collection|Language[]
*/
public function getLanguages(): Collection
{
return $this->languages;
}
public function addLanguage(Language $language): self
{
if (!$this->languages->contains($language)) {
$this->languages[] = $language;
}
return $this;
}
public function removeLanguage(Language $language): self
{
if ($this->languages->contains($language)) {
$this->languages->removeElement($language);
}
return $this;
}
}
语言:
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="App\Repository\LanguageRepository")
*/
class Language
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\ManyToMany(targetEntity="App\Entity\Project", mappedBy="languages")
*/
private $projects;
public function __construct()
{
$this->projects = new ArrayCollection();
}
/**
* @return Collection|Project[]
*/
public function getProjects(): Collection
{
return $this->projects;
}
public function addProject(Project $project): self
{
if (!$this->projects->contains($project)) {
$this->projects[] = $project;
$project->addLanguage($this);
}
return $this;
}
public function removeProject(Project $project): self
{
if ($this->projects->contains($project)) {
$this->projects->removeElement($project);
$projet->removeLangage($this);
}
return $this;
}
}
在我的数据库中,它们通过project_language相关联,并且在其中具有ID
这是我目前无法使用的查询:
$init = 'language_C_1';
$array = explode('_', $init);
$repo = $this->getDoctrine()->getRepository(Project::class);
$init = $array[2];
$query = $repo->createQueryBuilder('p')
->innerJoin('project_language', 'pl', Join::WITH, 'p.id = pl.project_id')
->innerJoin('language', 'l', Join::WITH, 'pl.language_id = l.id')
->where('l.id = :init')
->setParameter('init', $init)
->getQuery();
$arrayProjets = $query->getResult();
谢谢您的回答!
答案 0 :(得分:0)
Doctrine允许您对数据库进行抽象。您不应该考虑数据库表,而应该考虑实体: 您的项目实体具有$ languages属性,因此您可以像这样在您的queryBuilder中使用它:
$repo
->createQueryBuilder('p')
// add this to also load the languages entities
->addSelect('l')
->innerJoin('p.languages', 'l')
->where('l.id = :languageId')
->setParameter('languageId', $languageId)
->getQuery();
我对Product实体的属性$ languages进行了连接:连接表(此处为project_language)是完全透明的!