如何在Yii2-GridView中讓關聯字段帶搜索和排序功能?

ADVERTISEMENT

如何在Yii2-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'],
 ],
 ]); ?>

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持路飯。


本文地址:
ADVERTISEMENT