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'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With