我有两张桌子:
订单
- id
- client
- ...
行:
- orderID
- startDate
- endDate
- ...
在我的订单'控制器中,我添加了这两个以从每个订单行获取日期:
public function getStartDate()
{
return OrdersLines::find()
->andWhere(['orderID'=>$this->id])
->min('startDate');
}
public function getEndDate()
{
return OrdersLines::find()
->andWhere(['orderID'=>$this->id])
->max('endDate');
}
在我的索引视图中(使用kartik的grid和expandRowColumn),我显示了包含2个计算列的订单网格:
- start_Date:从每个订单的行获取更早的开始日期
- end_Date:从每个订单的行获取更高的结束日期
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'export' => false,
'columns' => [
[
'class' => 'kartik\grid\ExpandRowColumn',
'value' => function ($model, $key, $index, $column) {
return GridView::ROW_COLLAPSED;
},
'detail' => function ($model, $key, $index, $column) {
$searchModel = new OrdersLinesSearch();
$searchModel->orderID = $model->id;
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return Yii::$app->controller->renderPartial('_ordersLines', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
},
],
...
[
'attribute' => 'start_Date',
'format' => 'date',
'label' => 'Start Date',
'value' => 'startDate',
],
[
'attribute' => 'end_Date',
'format' => 'date',
'label' => 'End Date',
'value' => 'endDate',
],
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
如何设置OrdersSearch模型以允许使用这些值(start_Date和end_Date)进行排序?
答案 0 :(得分:1)
我认为您应该使用ActiveQuery中的join创建ActiveDataProvider,使用传递给action的sort参数:
$sort = \Yii::$app->request->get('sort');
if($sort == 'startDate') $having = 'MAX(startDate)';
if($sort == 'endDate') $having = 'MAX(endDate)';
$sql = Orders::find()->joinWith(['lines' => function($q) use($having) {
$q->having = $having;
}]);