首页 > 解决方案 > 在 symfony 4.1 上使用 queryBuilder 原则创建 leftjoin

问题描述

我正在尝试进行左连接,但我收到了这个 sql 错误 在此处输入图像描述

所以我有两个实体帖子和评论 1-帖子

<?php

 namespace App\Entity;

 use Doctrine\ORM\Mapping as ORM;
 use App\Utils\Slugger;
 use Symfony\Component\Validator\Constraints as Assert;
 use Symfony\Component\HttpFoundation\File\UploadedFile;

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

   /**
   * @ORM\Column(type="string", length=255,unique=true)
   */
   private $title;

我有更多的领域,但对于这个问题没有必要。

和评论实体

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

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


   /**
    * @ORM\ManyToOne(targetEntity="App\Entity\Post")
    */
    private $post;

在这个实体中,我有 ManyToOne 的关系,一切都很好。

所以我的问题是我试图在 PostRepository 上获取所有发表评论(我认为没有必要为一种方法创建 CommentRepository)这是我的 PostRepositoy

<?php
 namespace App\Repository;
 use App\Entity\Post;
 use App\Entity\Comments;
 use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
 use Symfony\Bridge\Doctrine\RegistryInterface;
 class PostRepository extends ServiceEntityRepository
 {
     public function __construct(RegistryInterface $registry)
     {
       parent::__construct($registry, Post::class);
     }

   public function findComments($post)
   {

    return $this->createQueryBuilder('p')
        ->leftJoin(Comments::class,'c')
        ->andWhere('c.post = :val')
        ->setParameter('val', $post)
        ->orderBy('p.id', 'ASC')
        ->getQuery()
        ->getResult()
        ;
   }

谁能帮我 ?我可以使用 dql 或 createQuery 并使用其他选项,但我想这样做,但我认为查询不正确。

标签: mysqlsymfonydoctrine

解决方案


推荐阅读