這篇文章主要介紹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'], ], ]); ?>
以上是“Yii2-GridView中如何實現讓關聯字段帶搜索和排序功能”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。