![](/img/trans.png)
[英]yii2 Basic - How to Display data in grid view column using id from other table?
[英]How to display data of another table in grid view in yii2?
在siteController
我編寫查詢並將dataProvider
數組傳遞給index.php
以顯示包含在表格中。 在index.php
我想顯示member name
而不是memberID
。 為此,我編寫了內部查詢,並成功在命令提示符下成功運行。這里我無法打印first name
而不是' member id
'
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'.' <b>'.$complaintModel.'</b> '.'Complaints',
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'practiceCode',
// 'memberID',
'description',
'status',
],
]); ?>
我通過dataProvider傳遞數據。
由於您使用的是強大的框架,因此您最好讓框架為您執行復雜的操作,而不是嘗試編寫自己的查詢。 這就是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將為您整理所有列名,並編寫查詢。
該查詢與dataProvider無關,因此無用
如果要擴展查詢,則應執行此操作並分配給dataprovider中使用的查詢,而不僅僅是執行查詢。 無論如何,你可以使用匿名函數獲取成員的名稱來檢索值;
<?= GridView::widget([
'dataProvider' => $dataProvider4,
//'summary'=>'Total'.' <b>'.$complaintModel.'</b> '.'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',
],
]);
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.