2016-04-06 190 views
0

我有兩個表:Yii2排序計算字段

訂單:

- 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'); 
    } 

在我的索引視圖(使用卡爾蒂克的網格和expandRowColumn)我展示訂單網格2計算列:

  • 起始日期:被越早開始從行日期爲每個訂單
  • 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)?

回答

1

我認爲你應該創建ActiveDataProvider在ActiveQuery使用連接,使用排序參數傳遞給動作:

$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; 
}]); 
+0

謝謝@法布里奇奧 - caldarelli。試圖按照下面的代碼,但是當我點擊結束日期或開始日期以列表排序列表它只顯示一個記錄,而不是按日期排序的所有記錄: $ sort = \ Yii :: $ app-> request->得到( '排序');如果(strpos($ sort,'start_Date')!== false)$ having ='MAX(startDate)';如果(strpos($ sort,'end_Date')!== false)$ having ='MAX(endDate)'; 如果(isset($具有)){ \t \t \t \t $查詢=訂單::尋找() - > joinWith([ 'ordersLines'=>功能($ q)的使用($具有){ \t \t \t \t \t $ q-> having = $ having; \t \t \t \t}]); \t \t \t} \t \t \t else $ query = Orders :: find(); – farrusete