Yii2-GridView 中让关联字段带搜索

情境要求:
要在订单(Order)视图的gridview中显示出客户(Customer)姓名,并使其具有与其它字段相同的排序和搜索功能。

数据库结构
订单表order含有字段customer_id 与 客户表customer的id字段关联

首先确保在Order Model中包含以下代码:

  1.  
    public function getCustomer()
  2.  
    {
  3.  
    return $this->hasOne(Customer::className(), ['id' => 'customer_id']);
  4.  
    }
  5.  
     

用gii会自动生成此代码;

第一步:
在OrderSearch添加一个$customer_name变量

  1.  
    class OrderSearch extends Order
  2.  
    {
  3.  
    public $customer_name; //<=====就是加在这里
  4.  
    }
  5.  
    //这里加上(不加不出现搜索框)
public function rules()
{
    return [
        [['id', 'admin_id', 'cat_id', 'add_time', 'update_time', 'listorder', 'status'], 'integer'],
        [['title', 'description', 'content', 'url', 'author'], 'safe'],
      [['customer_name'],'safe],//添加搜索字段规则 ]; }

 

第二步:
修改OrderSearch中的search函数

  1.  
    public function search($params)
  2.  
    {
  3.  
    $query = Order::find();
  4.  
  5. //$query->joinWith('custome');不生效
    $query->leftJoin('Customer','order.customer_id = customer.id');
  6.  
    $dataProvider = new ActiveDataProvider([
  7.  
    'query' => $query,
  8.  
    ]);
  9.  
     
  10.  
    $dataProvider->setSort([
  11.  
    'attributes' => [
  12.  
    /* 其它字段不要动 */
  13.  
    /* 下面这段是加入的 (自己推测做排序用的)*/
  14.  
    /*=============*/
  15.  
    'customer_name' => [
  16.  
    'asc' => ['customer.customer_name' => SORT_ASC],
  17.  
    'desc' => ['customer.customer_name' => SORT_DESC],
  18.  
    'label' => 'Customer Name'
  19.  
    ],
  20.  
    /*=============*/
  21.  
    ]
  22.  
    ]);
  23.  
     
  24.  
    if (!($this->load($params) && $this->validate())) {
  25.  
    return $dataProvider;
  26.  
    }
  27.  
     
  28.  
    $query->andFilterWhere([
  29.  
    'id' => $this->id,
  30.  
    'user_id' => $this->user_id,
  31.  
    'customer_id' => $this->customer_id,
  32.  
    'order_time' => $this->order_time,
  33.  
    'pay_time' => $this->pay_time,
  34.  
    ]);
  35.  
     
  36.  
    $query->andFilterWhere(['like', 'status', $this->status]);
  37.  
    $query->andFilterWhere(['like', 'customer.nick, $this->customer_name]) ;//<=====加入这句
  38.  
     
  39.  
    return $dataProvider;
  40.  
    }

第三步:
修改order/index视图的gridview

  1.  
    <?= GridView::widget([
  2.  
    'dataProvider' => $dataProvider,
  3.  
    'filterModel' => $searchModel,
  4.  
    'columns' => [
  5.  
    ['class' => 'yii\grid\SerialColumn'],
  6.  
    'id',
  7.  
    'customer_id',
  8.  
    'status',
  9.  
    ['label'=>'客户', 'attribute' => 'customer_name',
    'value'=>function($model){
    return isset($model->customer)?$model->customer->nick:'';
    }
    ],//<=====加入这句
  10.  
    ['class' => 'yii\grid\ActionColumn'],
  11.  
    ],
  12.  
    ]); ?>
  13.  
posted @ 2020-07-15 11:19  星云惊蛰  阅读(289)  评论(0)    收藏  举报