Yii2实现让关联字段支持搜索功能的方法


直接上代码

感谢 老胡哥,分享代码,记录一下,方便学习,且分享给大家

https://github.com/hubeiwei/hello-yii2/blob/2.0/models/search/SettingSearch.php
https://github.com/hubeiwei/hello-yii2/blob/2.0/modules/backend/views/setting/index.php

user主键id;setting表 外键updated_by

SettingSearch.php

<?php
namespace app\models\search;
use app\models\Setting;
use app\models\User;
use yii\base\Model;
use yii\data\ActiveDataProvider;
/**
 * SettingSearch represents the model behind the search form about `app\models\Setting`.
 */
class SettingSearch extends Setting
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'key', 'value', 'status', 'description', 'tag', 'updated_by', 'created_at', 'updated_at', 'username'], 'safe'],
        ];
    }
    /**
     * @inheritdoc
     */
    public function attributes()
    {
        return array_merge(parent::attributes(), [
            'username',
        ]);
    }
    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return array_merge(parent::attributeLabels(), [
            'username' => '操作人',
        ]);
    }
    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }
    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = self::find()
            ->from(['setting' => self::tableName()])
            ->select([
                'setting.*',
                'user.username',
            ])
            ->leftJoin(['user' => User::tableName()], 'user.id = setting.updated_by');
        // add conditions that should always apply here
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);
        $this->load($params);
        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }
        // grid filtering conditions
        $query->andFilterWhere([
            'setting.id' => $this->id,
            'setting.updated_by' => $this->updated_by,
            'user.username' => $this->getAttribute('username'),
        ]);
        $query->andFilterWhere(['like', 'key', $this->key])
            ->andFilterWhere(['like', 'value', $this->value])
            ->andFilterWhere(['like', 'setting.status', $this->status])
            ->andFilterWhere(['like', 'description', $this->description])
            ->andFilterWhere(['like', 'tag', $this->tag]);
        $query->timeRangeFilter('setting.created_at', $this->created_at, false)
            ->timeRangeFilter('setting.updated_at', $this->updated_at, false);
        return $dataProvider;
    }
}

index.php

<?php
use app\models\Setting;
use app\modules\core\helpers\RenderHelper;
use app\modules\core\widget\DateRangePicker;
use yii\helpers\Html;
use kartik\grid\SerialColumn;
use kartik\grid\ActionColumn;
/**
 * @var $this yii\web\View
 * @var $searchModel app\models\search\SettingSearch
 * @var $dataProvider yii\data\ActiveDataProvider
 */
$this->title = '网站配置';
$this->params['breadcrumbs'][] = ['label' => $this->title, 'url' => ['index']];
$gridColumns = [
    ['class' => SerialColumn::className()],
    [
        'attribute' => 'id',
        'headerOptions' => ['width' => 80],
    ],
    'key',
    'value',
    'description',
    'tag',
    [
        'attribute' => 'status',
        'value' => function ($model) {
            return Setting::$status_map[$model->status];
        },
        'filter' => RenderHelper::dropDownFilter('SettingSearch[status]', $searchModel->status, Setting::$status_map),
        'headerOptions' => ['width' => 100],
    ],
    'username',
    [
        'attribute' => 'created_at',
        'format' => 'dateTime',
        'filterType' => DateRangePicker::className(),
        'filterWidgetOptions' => [
            'dateOnly' => false,
        ],
        'headerOptions' => ['width' => 160],
    ],
    [
        'attribute' => 'updated_at',
        'format' => 'dateTime',
        'filterType' => DateRangePicker::className(),
        'filterWidgetOptions' => [
            'dateOnly' => false,
        ],
        'headerOptions' => ['width' => 160],
    ],
    ['class' => ActionColumn::className()],
];
?>
<div class="setting-index">

    <h1><?= Html::encode($this->title) ?></h1>

    <hr>

    <p>
        <?= Html::a('添加配置', ['create'], ['class' => 'btn btn-info']) ?>
    </p>

    <?= RenderHelper::gridView($dataProvider, $gridColumns, $searchModel) ?>
    
</div>

效果图


  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要给Yii2-GridView中的自定义字段增加排序功能,可以通过以下步骤实现: 1. 在GridView的columns属性中,为自定义字段添加‘attribute’属性(指定排序用的字段),‘label’属性(指定在表头显示的名称),以及‘value’属性(指定自定义字段的值)。 2. 在GridView的dataProvider属性中,为排序用的字段添加一个Sort属性。 3. 在GridView中的排序链接中,为自定义字段添加一个sort参数,指定排序用的字段。 以下是一个示例代码: ``` use yii\grid\GridView; use yii\data\ActiveDataProvider; use yii\data\Sort; $dataProvider = new ActiveDataProvider([ 'query' => $query, 'sort' => [ 'attributes' => [ 'custom_field' => [ 'asc' => ['custom_field' => SORT_ASC], 'desc' => ['custom_field' => SORT_DESC], 'label' => 'Custom Field', ], ], ], ]); echo GridView::widget([ 'dataProvider' => $dataProvider, 'columns' => [ 'id', 'name', [ 'attribute' => 'custom_field', 'label' => 'Custom Field', 'value' => function ($model) { return $model->customField; } ], ], 'sorter' => [ 'attributes' => [ 'custom_field' => [ 'asc' => ['custom_field' => SORT_ASC], 'desc' => ['custom_field' => SORT_DESC], ], ], ], ]); ``` 在以上代码中,我们为自定义字段‘custom_field’添加了一个Sort属性,然后在GridView中为该字段添加了‘attribute’、‘label’和‘value’属性。最后,在排序链接中为自定义字段添加了‘sort’参数,指定排序用的字段。这样就可以为Yii2-GridView中的自定义字段增加排序功能了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值