Yii2-GridView 中让关联字段带搜索和排序功能示例
程序员文章站
2024-03-06 17:22:50
情境要求:
要在订单(order)视图的gridview中显示出客户(customer)姓名,并使其具有与其它字段相同的排序和搜索功能。
数据库结构
订单表o...
情境要求:
要在订单(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'], ], ]); ?>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。