Yii2 -获得所有唯一模型属性值的最佳方法是什么?


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

我的模型FAQ有4个属性

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

现在我的actionIndex函数看起来像

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

我如何在控制器中使用Yii2或PHP获得$chapter的唯一值的数组?在sql中,它看起来像

SELECT DISTINCT chapter FROM ' faq_table'

可以这样做:

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

如果您希望结果为普通数组而不是包含常见问题模型的数组,您可以在->all()之前添加asArray()

运行下面的代码将显示它将生成这个确切的查询。

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

额外的评论。我也认为如果你想使用模型,最好删除$faq = Faq::find()->all();并使用$dataProvider->getModels()。这样,获取数据的查询就不会运行两次。