问题描述
为了显示我的 GridView,我使用了这个 ActiveDataProvider:
^M
我不知道如何在 Gridview 中使用 STRING_AGG() 函数生成的列。
为了以防万一,publicationsAuthor 关系是这样编码的:
:%s/^M/\r/g
我需要使用 STRING_AGG() 函数,因为我想在 Gridview 的一个单元格中显示许多作者。
我尝试以这种方式使用“作者”列:
public function search($params)
{
$query = PublicationsPublication::find()
->select(['eid','title','pubdate','citedby',"STRING_AGG(disTINCT(CONCAT(author.authid,' - ',authname)),',') AS authors"])
->joinWith('publicationsAuthor')
->groupBy(['eid','citedby']);
$dataProvider = new ActiveDataProvider([
'query' => $query,]);
$this->load($params);
if (!$this->validate()) {
return $dataProvider;
}
...
}
但不幸的是它没有奏效。在网格中,所有值都设置为“未设置”。该查询效果很好,因为我在 PgAdmin 中对其进行了测试。
解决方法
yii\data\ActiveDataProvider
与模型一起使用,因此默认情况下只有模型定义的字段可用。添加由某些表达式生成的字段的最简单方法是将同名的公共属性添加到您的模型中,如下所示:
class PublicationsPublication extends ActiveRecord
{
public $authors;
// ... other code in PublicationsPublication model ...
public function attributeLabels()
{
// You can also add label for new field
return [
'authors' => 'Authors',// ... other labels ...
];
}
}
公共属性 $authors
将加载 SQL 查询结果中来自字段 authors
的数据。然后你可以在网格中使用它作为任何其他字段。
另一种选择是使用 yii\data\SqlDataProvider
而不是 yii\data\ActiveDataProvider
。