[英]Yii2 - What is the best way to get all unique model attribute values?
My model FAQ has 4 attributes 我的模型FAQ有4个属性
* @property integer $id * @property string $chapter * @property string $question * @property string $answer
Right now my actionIndex function looks like 现在我的actionIndex函数看起来像
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? 如何在Controller中使用Yii2或PHP获取$ chapter的唯一值数组? Lets say in sql it looks like 让我们说在sql看起来像
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()
. 如果您希望结果为纯数组而不是包含Faq模型的数组,则可以在->all()
之前添加asArray()
->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();
我也认为最好删除$faq = Faq::find()->all();
and use $dataProvider->getModels()
if you want to use the models. 如果要使用模型,请使用$dataProvider->getModels()
。 This way the query to fetch the data isn't run twice. 这样,获取数据的查询不会运行两次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.