Yii2 - What is the best way to get all the unique values โ€‹โ€‹of model attributes?

My FAQ model has 4 attributes

* @property integer $id * @property string $chapter * @property string $question * @property string $answer

Now my actionIndex function looks like

 public function actionIndex() { $faq = Faq::find()->all(); $dataProvider = new ActiveDataProvider([ 'query' => Faq::find(), ]); return $this->render('index', [ 'dataProvider' => $dataProvider, 'faq' => $faq ]); } 

How can I get an array of unique $ chapter values โ€‹โ€‹using Yii2 or PHP in the controller? Suppose in sql it looks like

SELECT DISTINCT chapter FROM ' faq_table'

+8
arrays sql php activerecord yii2
source share
1 answer

This can be done as follows:

 Faq::find()->select('chapter')->distinct()->all(); 

If you want the results as a simple array instead of an array containing Faq models, you can add asArray() to ->all() .

By running the code below, you will see that it issues this exact request.

 Faq::find()->select('chapter')->distinct()->createCommand()->getSql(); 

Additional comment. I also think that it is better to delete the line $faq = Faq::find()->all(); and use $dataProvider->getModels() if you want to use models. Thus, a query to fetch data is not performed twice.

+14
source share

All Articles