我是 Symfony 的新手,正在尝试执行基本的左连接,以根据 Jobs 表中的 client_id 拉入客户端名称。
App\Entity\Jobs
:
class Jobs
{
/**
* @ORM\Column(type="integer")
* @ORM\ManyToOne(targetEntity="App\Entity\Clients", inversedBy="jobs")
* @ORM\JoinColumn(nullable=false)
*/
private $client;
应加入App\Entity\Clients
:
class Clients
{
/**
* @ORM\Column(type="integer")
* @ORM\OneToMany(targetEntity="App\Entity\Jobs", mappedBy="client")
*/
private $jobs;
在我的App\Repository\JobsRepository
类中,以下函数正在尝试左连接:
use App\Entity\Jobs;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Symfony\Bridge\Doctrine\RegistryInterface;
class JobsRepository extends ServiceEntityRepository
{
public function __construct(RegistryInterface $registry)
{
parent::__construct($registry, Jobs::class);
}
public function allWithClientName()
{
return $this->createQueryBuilder('job')
->leftJoin('job.client_id', 'client')
->getQuery()
->execute();
}
}
我返回的错误是:
[Semantical Error] line 0, col 60 near 'client': Error: Class App\Entity\Jobs has no association named client_id
有什么想法吗?据我有限的理解,注释应该形成所需的连接。
最佳答案
我没有看到任何获取实体管理器的调用。
您要么忘记在 createQueryBuilder()
之前调用 getRepository()
,要么忘记在查询中添加 from
。
避免使用可能被误认为实体名称的别名
使用双引号括住您的查询。因为当您碰巧编写类似 where('e.param="string"')
之类的内容时,您会遇到错误,因为 DQL 中的字符串不允许使用双引号。
将 $client_id
更改为 $client
。按照 Doctrine 的运作方式,如果保持原样,更新架构时您将拥有 client_id_id
作为 SQL 列。
避免复数实体...Donctrine不喜欢它们...;)
这是完整的代码更正
工作
class Jobs {
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Clients", inversedBy="id")
* @ORM\JoinColumn(nullable=false)
*/
private $client;
}
客户端
class Clients {
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
*@ORM\OneToMany(targetEntity="App\Entity\Jobs", mappedBy="client")
*/
private $jobs
}
JobsRepository 解决方案 1
use App\Entity\Jobs
class JobsRepository extends \Doctrine\ORM\EntityRepository {
public function repoQuery() {
$em=$this->getEntityManager();
return $em->getRepository(Jobs::class)
->createQueryBuilder("j")
->leftJoin("j.client", "c")
->getQuery()
->execute();
}
}
JobsRepository 解决方案 2
use App\Entity\Jobs
class JobsRepository extends \Doctrine\ORM\EntityRepository {
public function repoQuery() {
$em=$this->getEntityManager();
return $em->createQueryBuilder()
->from(Jobs::class, "j")
->leftJoin("j.client", "c")
->getQuery()
->execute();
}
}
关于symfony - 我的左连接在 Symfony 4 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50407056/