Skip to content
Advertisement

Yii2, how to add a LIMIT on a leftjoin to get only 1 result back

I am trying to get all records from the product table, these records are unique but i use a leftjoin to add a second table with images of these products but when I do it will return some products more than once as some products have 1 or more images. How can I use a limit on the product_images table to make sure it will just get 1 image instead of all. The example below does not work so is this possible?

JavaScript

Advertisement

Answer

It can be solved by sub queries:

JavaScript

You have to use composit indexes on the table product_images to have goood performance.

You could use other sorting as order by id, e.g. you could introduce an ordering field in the table product_images.

I think a.id = b.id and a.id = c.id was a simple mistake. It’s about a.id = b.product_id and a.id = c.product_id.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement