【问题标题】:Yii2 - What is the best way to get all unique model attribute values?Yii2 - 获取所有唯一模型属性值的最佳方法是什么?
【发布时间】:2015-11-08 13:23:57
【问题描述】:

我的模型常见问题解答有 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
    ]);
}

如何在 Controller 中使用 Yii2 或 PHP 获取 $chapter 的唯一值数组?让我们在 sql 中说它看起来像

SELECT DISTINCT chapter FROM ' faq_table'

【问题讨论】:

    标签: php sql arrays activerecord yii2


    【解决方案1】:

    这可以这样完成:

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

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

    运行下面的代码会告诉你它会产生这个精确的查询。

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

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

    【讨论】:

    • 此查询返回一个活动记录数组。是否存在返回具有列值的数组的方法? ['chapter1','chapter2']
    • 好的,我找到了解决办法:Faq::find()->select('chapter')->distinct()->asArray()->column();
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-24
    • 1970-01-01
    • 2022-06-20
    • 1970-01-01
    相关资源
    最近更新 更多