我想将公司表名加入员工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;
}
http://localhost/test/web/employee/
显示在公司字段中(未设置) 请帮助我
答案 0 :(得分:1)
你可以用两种不同的方式做到这一点:1。如果要使用活动记录,则必须在要选择它的第一个模型中设置属性,并使用以下内容连接表:
public $ pin;
然后当你获得数据时,你可以访问第二个表中的pin
第二种方法是使用asArray()返回两个表中的所有关闭数据 $ model = News :: find() - &gt; leftJoin(&#39; comment&#39;,&#39; news.id = comment.news_id&#39;) - &gt; asArray() - &gt; all() ; 然后你可以在gridview中使用它
答案 1 :(得分:0)
你应该添加一个getter,例如:getCompanyname()n你的基础模型
......
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 /*
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/