《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.vephp.com/jiaocheng/1926.html