2

I'm using this native SQL query on symfony (Which is a really bad practice) but I'm struggling to get it running with DQL without triggering several errors.

SELECT Image.path, Image.name 
FROM Image
LEFT JOIN ImageVoters ON Image.id = ImageVoters.image_id
WHERE ImageVoters.voter_id =1
AND ImageVoters.action =  'favourite'
ORDER BY Image.created_at ASC

This is what I've got so far

    public function findMyFavourites()
    {
       return $this->getEntityManager()
       ->createQuery('SELECT p.path,p.name 
       FROM GabrielUploadBundle:Image p 
       LEFT JOIN GabrielUploadBundle:ImageVoters v 
       ON p.id  = v.image_id 
       WHERE v.action ="favourite" 
       ORDER BY p.created_at ASC')
       ->getResult();
    }

It throws this error for some reason

Error: Expected Doctrine\ORM\Query\Lexer::T_WITH, got 'ON'

This is the query that works

$em = $this->getDoctrine()->getManager();
$query = $em->getRepository('GabrielUploadBundle:Image')->createQueryBuilder('p')
    ->select(array('p.path', 'p.name','p.id','p.upvotes','p.imageowner','p.createdAt','p.updatedAt'))
    ->leftJoin('GabrielUploadBundle:ImageVoters', 'v', 'WITH', 'p.id = v.image_id')
    ->where("v.action = 'favourite'")
    ->andWhere("v.voter_id = 1")
    ->orderBy('p.createdAt', 'ASC')
    ->getQuery();
2
  • Your query seems correct just change ON to WITH Commented Apr 17, 2014 at 18:18
  • already tried that got [Syntax Error] line 0, col 204: Error: Expected Literal, got '"' Commented Apr 17, 2014 at 18:33

2 Answers 2

2

If you change ON to WITH your query will be OK.
You can also try

$query = $em->getRepository('GabrielUploadBundle:Image')->createQueryBuilder('p')
   ->select(array('p.path', 'p.image'))
   ->leftJoin('GabrielUploadBundle:ImageVoters', 'v', 'WITH', 'p.id = v.image_id')
   ->where("v.action = 'favourite'")
   ->orderBy('p.createdAt', 'ASC')
   ->getQuery();
$result = $query->getResult();
Sign up to request clarification or add additional context in comments.

4 Comments

your query does have a lot of syntax errors, but it sure helped me get it done, check the "fixed" version on the edited answer
im selecting a few more fields tho.
You're right but those error which you say are because I don't know what do you have in your mapping for fields so I used the column names, and I thought in your mapping there is a relation between Image and ImageVoters; anyway I updated my answer, too :)
I think you forgot the "WHERE ImageVoters.voter_id =1" part sir
0

pIn addition, if you have a relation between your Image model and ImageVoters model in Image Entity class, you can just do:

->leftJoin('p.imageVoters', 'v')

Doctrine will do the rest for you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.