《PHP實戰:Yii2-GridView 中讓關聯字段帶搜索和排序功能示例》要點:
本文介紹了PHP實戰:Yii2-GridView 中讓關聯字段帶搜索和排序功能示例,希望對您有用。如果有疑問,可以聯系我們。
相關主題:YII框架
情境要求:
PHP編程
要在訂單(Order)視圖的gridview中顯示出客戶(Customer)姓名,并使其具有與其它字段相同的排序和搜索功能.PHP編程
數據庫結構
PHP編程
訂單表order含有字段customer_id 與 客戶表customer的id字段關聯PHP編程
首先確保在Order Model中包含以下代碼:PHP編程
public function getCustomer() { return $this->hasOne(Customer::className(), ['id' => 'customer_id']); }
用gii會自動生成此代碼;PHP編程
第一步:
PHP編程
在OrderSearch添加一個$customer_name變量PHP編程
class OrderSearch extends Order { public $customer_name; //<=====就是加在這里 }
第二步:
PHP編程
修改OrderSearch中的search函數PHP編程
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; }
第三步:
PHP編程
修改order/index視圖的gridviewPHP編程
<?= 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'], ], ]); ?>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持維易PHP.
PHP編程
轉載請注明本頁網址:
http://www.snjht.com/jiaocheng/1926.html