您的位置:首页 > 编程语言 > PHP开发

Yii2-GridView 自定义关联字段带搜索和排序功能

2016-09-18 11:41 751 查看
要在订单(Order)视图的gridview中显示出客户(Customer)姓名,并使其具有与其它字段相同的排序和搜索功能。

数据库结构

订单表order含有字段customer_id 与 客户表customer的id字段关联

首先确保在Order Model中包含以下代码:

public function getCustomer()
{
return $this->hasOne(Customer::className(), ['id' => 'customer_id']);
}

用gii会自动生成此代码;

第一步:

在OrderSearch添加一个$customer_name变量

class OrderSearch extends Order
{
public $customer_name;
}

第二步:

修改OrderSearch中的search函数

public function search($params)
{
$query =  Order::find();
$query->joinWith(['customer']); //添加代码
$dataProvider = new ActiveDataProvider([
'query' => $query,   //$query必须返回ActiveQuery
]);

$dataProvider->setSort([
'attributes' => [
/* 指定其它字段 */
/* 加入 */
/*=============*/
'customer_name' => [
'asc' => ['customer.customer_name' => SORT_ASC],  //table.字段,若行记录字段名唯一,可略table
'desc' => ['customer.customer_name' => SORT_DESC],
'label' => 'Customer Name'
],
/*=============*/
]
]);

if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}

$query->andFilterWhere([
'id' => $this->id,
'user_id' => $this->user_id,
'customer_id' => $this->customer_id,
'order_time' => $this->order_time,
'pay_time' => $this->pay_time,
]);

$query->andFilterWhere(['like', 'status', $this->status]);
$query->andFilterWhere(['like', 'customer.customer_name', $this->customer_name]) ;   //添加代码,table.字段,若行记录字段名唯一,可略table

return $dataProvider;
}

第三步:

修改order/index视图的gridview

<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'customer_id',
'status',
['label'=>'客户',  'attribute' => 'customer_name',  'value' => 'customer.customer_name' ],//添加代码,table.字段,若行记录字段名唯一,可略table

['class' => 'yii\grid\ActionColumn'],
],
]); ?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: