S
S
Sergey Sviridonov2017-12-26 11:33:58
JavaScript
Sergey Sviridonov, 2017-12-26 11:33:58

How to display records by filtering out copies of a specific field in yii2?

Good afternoon!
I'm trying to display records, filtering out copies:

$query = Product::find();
    
    $pages = new Pagination([
      'totalCount' => $query->count(),
      'pageSize' => 15,
      'forcePageParam' => false,
      'pageSizeParam' => false,
    ]);
    
    $products = $query->offset($pages->offset)->limit($pages->limit)->all();
    
    return $this->render('index', [
      'products' => $products,
      'pages' => $pages,
    ]);

Table:
id code name price quantity desc sale
I tried groupBy, but I want to display the products with the lowest price.
Task: Get all products so that the code field is not duplicated (there are many records with the same code field - product code) you need to get products with a low price for each code.
Something like this, but only with all fields (for my task)
SELECT code_medication, MIN(price) FROM tailings t GROUP BY code_medication LIMIT 50;

ps so that pagination would work. Any ideas? And then he broke his head.
Thank you very much in advance

Answer the question

In order to leave comments, you need to log in

4 answer(s)
K
Konstantin, 2019-10-17
@just_konstantin

The error is thrown inside the handleClose function . You are trying to pass a non-existent function to the console. Hence this error

V
Vladimir, 2019-10-17
@Casufi

Mistake number 1 - remove the word "public"
Mistake number two - never do
this

A
Andrew, 2017-12-26
@HTMLord

SELECT DISTINCT code_medication, MIN(price) FROM tailings t GROUP BY code_medication LIMIT 50;

Product::find()
->distinct()
->select('code, MIN(price)')
->from('product')
->groupBy('code');

$subQuery = (new Query())->select('MIN(t2.price)')->from('tailings t2')->where('t2.code_medication = t.code_medication');
$query = Product::find()->from('tailings t')->where(['t.price' =>  $subQuery])->groupBy('t.code_medication');

$countQuery = clone $query;

$pages = new Pagination([
      'totalCount' => $countQuery->count(),
      'pageSize' => 15,
      'forcePageParam' => false,
      'pageSizeParam' => false,
    ]);
    
$products = $query->offset($pages->offset)->limit($pages->limit)->all();

N
Nikita, 2017-12-26
@Rema1ns

distinct() on the model's code_medication field

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question