简体   繁体   中英

Doctrine Query builder error when using joins

In a photocontest have a vote entity that has the "imageId" field.

I would like to get a query containing the id of the vote and the fileName of the image which Id the vote carries. The entity looks like this:

class Vote
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    public $id;
    /**
     * @ORM\Column(type="integer", name="image_id")
     * @var integer $imageId
     * @ORM\ManyToOne(targetEntity="Image")
     * @ORM\JoinColumn(name="image_id", referencedColumnName="id")
     */
    protected $imageId;

    /**
     * @ORM\Column(type="datetime", name="date")
     */
    protected $date;

And the image it is linking to like this:

class Image {

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    public $id;
    /**
     * @ORM\Column(type="string", length=255, name="file_name")
     * @var string $fileName
     */
    protected $fileName;

Now I was trying to get the results out by using this query builder:

$votes = $qb -> select("v.id, i.fileName, v.date")
    ->from("AppBundle:Vote", "v")
    ->join("AppBundle:Image", "i")
    ->orderBy("v.id", "DESC")
    ->getQuery();

Using it in this configuration gives me an error saying:

Expected Literal, got 'BY'

But after removing the orderBy I get this result

Error: Expected Doctrine\\ORM\\Query\\Lexer::T_WITH, got end of string.

I am aware that the error links to the fact that I didn't use the WITH param inside the join, but would like this to work 100% good and having it go fully through docrine relationships.

Whay could be the problem and how can I fix it?

I think it's because in your entity, your imageId field is defined twice in doctrine :

@ORM\Column(type="integer", name="image_id")

and

@ORM\JoinColumn(name="image_id", referencedColumnName="id")

You have to remove the first one (@ORM\\Column) since its a join relation.

Plus, you have to defined it this way :

/**
 * @var Image
 *
 * @ORM\ManyToOne(targetEntity="Image")
 * @ORM\JoinColumn(name="image_id")
 */
protected $image;

You don't need more than that.

And in your VoteRepo :

$qb = $qb = $this->createQueryBuilder('v')
    ->select('v.id, i.fileName, v.date')
    ->join('v.image', 'i')
    ->orderBy('v.id', 'DESC');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM