GridView 关联字段搜索排序需求
需求场景:
需要在订单(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,
]);
$dataProvider->setSort([
'attributes' => [
/* 其它字段不要动 */
/* 下面这段是加入的 */
/*=============*/
'customer_name' => [
'asc' => ['customer.customer_name' => SORT_ASC],
'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]) ;//<=====加入这句
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' ],//<=====加入这句
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。