在Yii2中,我生成了一个model/view/controller
for表。view/index.php
显示:
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii'grid'SerialColumn'],
'username',
'type',
'clientid',//a foreign key to the table client
['class' => 'yii'grid'ActionColumn'],
],
]); ?>
当然,我想显示一个来自客户端的名称,而不是来自客户端的名称。这很简单:我必须写'client.name'
而不是'clientid'
,它是固定的。但是,我不能再对列进行排序或过滤了。
我如何排序/筛选引用另一个表的列?
您需要在GridView
[
'attribute' => 'clientid',
'value' => 'client.name',
]
另一个代码添加了搜索模型,并将clientid
属性放在safe
中,如
public function rules()
{
return [
['clientid', 'safe'],
];
}
并在search()
函数中添加以下代码:
$query->joinWith(['client(relation_name)']);
....
$query->andFilterWhere(['like', 'client.name (table_name.field_name)', $this->clientid]);
需要在搜索模型中声明$client。
in base Model:
public function getClient()
{
return $this->hasOne(Client::className(), ['id' => 'clientid']);
}
in search Model:
public $client;
public function rules()
{
parent::rules();
return array_merge(
[
[['client', ], 'safe'],
]
);
}
搜索功能:
$query->joinWith('client');
$query->andFilterWhere([
'client_id' => $this->client_id,
->andFilterWhere(['like', 'client.name', $this->client]);
在视图:[
'attribute' => 'client',
'label' => 'client name',
'value' => 'client.name',
]
我希望这对你有帮助。
来源:http://www.yiiframework.com/wiki/621/filter-sort-by-calculated-related-fields-in-gridview-yii-2-0/