Yii2-GridView 中讓關聯(lián)字段帶搜索和排序功能示例
情境要求:
要在訂單(Order)視圖的gridview中顯示出客戶(Customer)姓名,并使其具有與其它字段相同的排序和搜索功能。
數(shù)據(jù)庫結構
訂單表order含有字段customer_id 與 客戶表customer的id字段關聯(lián)
首先確保在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函數(shù)
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'],
],
]); ?>
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
- Yii2.0小部件GridView(兩表聯(lián)查/搜索/分頁)功能的實現(xiàn)代碼
- yii2實現(xiàn)分頁,帶搜索的分頁功能示例
- Yii2實現(xiàn)同時搜索多個字段的方法
- Yii2實現(xiàn)讓關聯(lián)字段支持搜索功能的方法
- Yii2 ActiveRecord多表關聯(lián)及多表關聯(lián)搜索的實現(xiàn)
- 淺析Yii2 GridView實現(xiàn)下拉搜索教程
- yii2實現(xiàn)根據(jù)時間搜索的方法
- yii2帶搜索功能的下拉框?qū)嵗斀?/a>
- Yii2框架整合Xunsearch搜索引擎的方法
- yii2組件之下拉框帶搜索功能的示例代碼(yii-select2)
- Yii2.0框架實現(xiàn)帶分頁的多條件搜索功能示例
相關文章
Laravel框架實現(xiàn)修改登錄和注冊接口數(shù)據(jù)返回格式的方法
這篇文章主要介紹了Laravel框架實現(xiàn)修改登錄和注冊接口數(shù)據(jù)返回格式的方法,結合實例形式分析了Laravel框架針對登錄與注冊接口數(shù)據(jù)操作流程、原理與修改操作實現(xiàn)方法,需要的朋友可以參考下2018-08-08
laravel框架學習筆記之組件化開發(fā)實現(xiàn)方法
這篇文章主要介紹了laravel框架學習筆記之組件化開發(fā)實現(xiàn)方法,結合實例形式分析了laravel框架組件化開發(fā)相關的實現(xiàn)步驟與操作注意事項,需要的朋友可以參考下2020-02-02
THINKPHP5分頁數(shù)據(jù)對象處理過程解析
這篇文章主要介紹了THINKPHP5分頁數(shù)據(jù)對象處理過程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-10-10

