Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 - What is the best way to get all unique model attribute values?

My model FAQ has 4 attributes

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

Right 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 values of $chapter using Yii2 or PHP in Controller? Lets say in sql it looks like

SELECT DISTINCT chapter FROM ' faq_table'

like image 209
st.limp Avatar asked Aug 15 '15 11:08

st.limp


1 Answers

This can be done like this:

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

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

Running the code below will show you it'll produce this exact query.

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

Extra comment. I also think it's better to remove the line $faq = Faq::find()->all(); and use $dataProvider->getModels() if you want to use the models. This way the query to fetch the data isn't run twice.

like image 92
Jap Mul Avatar answered Oct 21 '22 20:10

Jap Mul