[英]how to join table in grid view in yii2
我想將我的公司表名稱加入員工ID。 這是我在員工模型中的代碼
public function attributeLabels()
{
return [
'id' => 'ID',
//'company_id' => 'Company ID',
'emp_name' => 'Emp Name',
'emp_email' => 'Emp Email',
'emp_salery' => 'Emp Salery',
];
}
public function getCompany()
{
return $this->hasOne(Company::className(),['id' => 'company_id']);
}
在索引文件中,我使用此代碼
<?php PJax::begin();?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
//['class' => 'yii\grid\SerialColumn'],
//'id',
[
'attribute' => 'company_id',
'value' => 'company.name',
],
'emp_name',
'emp_email:email',
'emp_salery',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
<?php PJax::end();?></div>
在員工搜索表中,我使用此代碼
public function search($params)
{
$query = Employee::find();
$query->joinWith(['company']);
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
$query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
]);
$query->andFilterWhere(['like', 'company_id', $this->company_id])
->andFilterWhere(['like', 'emp_name', $this->emp_name])
->andFilterWhere(['like', 'emp_email', $this->emp_email])
->andFilterWhere(['like', 'emp_salery', $this->emp_salery])
->andFilterWhere(['like', 'Company.name', $this->company_id])
->andFilterWhere(['like', 'company.name', $this->company])
;
return $dataProvider;
}
是公司領域的節目(未設置)請幫助我
您可以通過兩種不同的方式執行此操作:1。 如果要使用活動記錄,則必須在第一個模型中設置屬性,然后選擇該屬性並將其與表連接:
公開的$ pin;
那么當您獲取數據時,您可以訪問第二張表中的圖釘
第二種方法是使用asArray()返回兩個表中的所有數據$ model = News :: find()-> leftJoin('comment','news.id = comment.news_id')-> asArray()- >所有(); 然后可以在gridview中使用它
您應該在基本模型中添加一個getter,例如:getCompanyname()
......
public function attributeLabels()
{
return [
'id' => 'ID',
//'company_id' => 'Company ID',
'emp_name' => 'Emp Name',
'emp_email' => 'Emp Email',
'emp_salery' => 'Emp Salery',
'companyName' => 'Company Name')
];
}
public function getCompany()
{
return $this->hasOne(Company::className(),['id' => 'company_id']);
}
您應該為公司名稱添加一個吸氣劑
/*
Getter for company name
*/
public function getCommpanyName() {
return $this->company->name;
}
在您的gridview中,您應該使用新的獲取名稱(companyName)
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
'companyName',
'emp_name',
'emp_email:email',
'emp_salery',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
請參閱此以獲得更完整的示例http://www.yiiframework.com/wiki/621/filter-sort-by-calculated-related-fields-in-gridview-yii-2-0/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.