V
V
Vitaly Kamelin2015-04-13 13:06:24
Yii
Vitaly Kamelin, 2015-04-13 13:06:24

How to select unique values ​​via ActiveRecord in Yii2?

It is necessary to make a selection of unique values, i.e. using DISTINCT. I have not found anywhere how this can be done using ActiveRecord without resorting to createCommand ().

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander N++, 2015-04-13
@turboGadjet

// SELECT DISTINCT `user_id` ...
$query = new Query();
$query->select('user_id')->distinct();

I
Igor Vasiliev, 2017-03-26
@Isolution666

I didn't reinvent the wheel. It turned out that displaying a list of records through a loop is so simple and easy and elementary)) Duplicate records disappear, only a list of unique records remains!

public function actionPage(){
        $select = City::find()->select(['obl'])->distinct()->all();
        return $this->render('page', ['select' => $select,]);
    }

Let me explain a little City is a model that accesses a certain table in the
<select class="form-control">
                    <?php foreach ($select as $m) { ?>
                        <option value="<?=$m->obl;?>"><?=$m->obl;?></option>
                    <?php } ?>
                </select>

Tested personally, it works! The count of unique records is:
--
--
I took it from the Yii documentation, I draw knowledge there, who did I help? )) I was glad to be useful. Good luck!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question