Yii2按计算的相关字段排序
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Yii2按计算的相关字段排序相关的知识,希望对你有一定的参考价值。
在过去的几个小时里,我正在尝试创建一个gridview可排序的计算列而没有成功,我尝试了每个指南,按照完全相同的步骤,没有得到任何软件。
计算的关系:
public function getOrderAmount() {
return $this->hasMany(Transaction::className(), ['user_id' => 'id'])->sum('sum');
}
UserSearch模型:
class UserSearch extends User
{
public $orderAmount;
public function rules()
{
return [
[['id'], 'integer'],
[['orderAmount'], 'safe'],
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
return Model::scenarios();
}
public function search($params)
{
$query = User::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$dataProvider->setSort([
'attributes'=>[
'id',
'name',
'orderAmount'=>[
'asc'=>['orderSum.order_amount'=>SORT_ASC],
'desc'=>['orderSum.order_amount'=>SORT_DESC],
'label'=>'Order Name'
]
]
]);
$this->load($params);
if (!$this->validate()) {
return $dataProvider;
}
$query->andFilterWhere(['orderSum.order_amount'=>$this->orderAmount]);
return $dataProvider;
}
}
风景:
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'responsive' => true,
'hover' => true,
'perfectScrollbar' => true,
'columns' => [
'orderAmount',
],
]); ?>
这是我在http://webtips.krajee.com/filter-sort-summary-data-gridview-yii-2-0/上面的示例中遵循的指南
我有一个错误:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'orderSum.order_amount' in 'order clause'
The SQL being executed was: SELECT * FROM `tbl_users` WHERE `id` IN ('1', '56') ORDER BY `orderSum`.`order_amount` LIMIT 20
注意:我删除了其他代码块以便于调试。
以上是关于Yii2按计算的相关字段排序的主要内容,如果未能解决你的问题,请参考以下文章
Yii2 Activerecord 从联结表中获取字段并根据它们排序