2015-12-24 50 views
4

siteController我寫查詢並將dataProvider的數組傳遞給index.php以顯示包含表格形式。在index.php我想顯示member name而不是memberID。對於我寫的內部查詢併成功地在命令提示運行successfully.Here我無法打印first name而不是「member id如何在yii2的網格視圖中顯示另一個表的數據?

 public function actionIndex() 
     {    
    $query = new \yii\db\Query; 
     $query->select(['member.firstName', 
        'complaint.practiceCode','complaint.id', 
        'complaint.description','member.firstName']) 
      ->from(['complaint']) 
      ->innerJoin(['member','complaint.memberID = member.id']) 
      ->groupBy(['complaint.id']) 
      ->where(['complaint.deleted' => 'N']); 
    $query->createCommand(); 

在這裏,我必須通過創建$dataProvider4通的數據,但我不能設置值firstName而不是memberID

 $dataProvider4= new ActiveDataProvider([ 
      'query' => $query, 
      'pagination' => false, 
     ]); 

     return $this->render('index', [ 
     'dataProvider4'=>$dataProvider4]); 

<?= GridView::widget([ 
    'dataProvider'=>$dataProvider4, 
    'summary'=>'Total'.'&nbsp<b>'.$complaintModel.'</b>&nbsp'.'Complaints', 
    'columns' => [ 
     ['class' => 'yii\grid\SerialColumn'], 
      'practiceCode', 
      // 'memberID', 
      'description', 
      'status', 
     ], 
    ]); ?> 

我已經通過dataProvider傳遞數據。

+0

發佈gridview的完整代碼 – GAMITG

回答

1

由於您使用的是強大的框架,因此您最好讓框架爲您處理複雜的事情,而不是嘗試編寫自己的查詢。這是Yii的設計目的。在你的行動中試試這個。

public function actionIndex() 
    {    
    $query = Member::find()-> 
     ->select(['firstName', complaint.practiceCode', complaint.id', 'complaint.description']) 
     ->groupBy(['complaint.id']) 
     ->joinWith('complaints')//Tells Yii to use the complains relation that we define below. By default it is an inner join 
     ->where(['complaint.deleted' => 'N']); 

$dataProvider= new ActiveDataProvider([ 
    'query' => $query, 
    'pagination' => false, 
]); 

return $this->render('index', [ 
    'dataProvider4'=>$dataProvider]); 

在您的模型中,您將需要定義一個關係,您可以在查詢中使用;

public function getComplaints(){ 
    return $this->hasMany(Complaints::className(), 'memberID' => 'id'); 
} 

這很有用,因爲它可以讓你得到抱怨,而無需編寫自己的查詢來獲取它們。

Yii會爲您整理所有列名,並編寫查詢。

+0

感謝它的工作 –

0

查詢是不相關的數據提供程序,然後是無用

如果你想延長你應該這樣做,並分配給數據提供程序不僅用於執行查詢的查詢查詢。 無論如何,你可以使用匿名函數獲取成員的名稱檢索值;

<?= GridView::widget([ 
     'dataProvider' => $dataProvider4, 
     //'summary'=>'Total'.'&nbsp<b>'.$complaintModel.'</b>&nbsp'.'Complaints', 
     'columns' => [ 
      ['class' => 'yii\grid\SerialColumn'], 
      'practiceCode', 
      /* ['attribute' => '', 
      'value' => function ($model) { 
       $myMemberModel = Member::find()-> 
         where(['id'=> $model->memberID ])->one(); 
       if (isset($myMemberModel) { 
        return $myMemberModel->firtsName; 
       } else { 
       return ' id : '. $model->memberID . ' do not match '; 
       } 
      }],*/ 
       'firstName', 
       'memberID', 
       'description', 
       'status', 
       ], 
     ]); 
?> 
+0

其實我已經通過dataProvider傳遞數據。我沒有添加上面這個dataProvider函數......我添加了這個網格視圖更改但仍然不工作 –

+0

什麼是錯誤 – scaisEdge

+0

我已更新答案使用成員檢索用戶名。 – scaisEdge

相關問題