yii2 limit not working correctly

Hi guys! In my app limit not worked correctly. My query:

$products = Product::find()





            ->filterWhere(['in', 'product_category_property_id', $filter])

            ->andFilterWhere(['product_category_link.category_id' => $category])

            ->andFilterWhere(['between', 'price', $cost_from, $cost_to])

            ->andFilterWhere(['hit' => $on_top])

            ->andFilterWhere(['in', 'brand_id', $get_brands]);

        $count = clone $products;

        $pagination = new Pagination([

            'defaultPageSize' => 12,

            'totalCount' => $count->count(),


        $models = $products->orderBy(['created_at' => SORT_DESC])




If I try without pagination with limit problem is similar too. But without limit everthing ok. If I remove all joins limit works correctly

Hi farkhodjon, welcome to the forum.

When you use joinWith for hasMany relations, limit may not work as expected, because the result set of the query may have duplicated entries from the main table.

product   category

A         X

B         Y

C         X

C         Y

C         Z

In the above, limit(5) will retrieve 3 products, not 5.

An easy solution for it may be adding "distinct" to the query.

products = Product::find()




Take a look at the following wiki.

Yii 2.0: Drills : Search by a HAS_MANY relation in Yii 2.0


It helps, thank you