Yii2 framework learning 4-1 modelSearch class learning custom search, associated query

1. Data provider, such as used in modelsearch class

 

 

 

 

 

 

 

 

 

 

<?php

namespace common\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Post;

/**
 * PostSearch represents the model behind the search form about `common\models\Post`.
 */
class PostSearch extends Post
{

    //增加数据的字段属性
    public function attributes()
    {
        return array_merge(parent::attributes(), ['author_name']);
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'status', 'create_time', 'update_time', 'author_id'], 'integer'],
            [['title', 'content', 'tags', 'author_name'], 'safe'],
        ];
    }

    /**
     * @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 = Post::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
             'pagination' => [
                'pageSize' => 10,
             ]
        ]);

        $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([
            'id' => $this->id,
            'status' => $this->status,
            'create_time' => $this->create_time,
            'update_time' => $this->update_time,
            'author_id' => $this->author_id,
        ]);

        $query->andFilterWhere(['like', 'title', $ this- > title])
             -> andFilterWhere (['like', 'content', $ this- > content])
             -> andFilterWhere (['like', 'tags', $ this- > tags]); 

        // add custom query 
        $ query -> the Join ( 'the INNER the JOIN', 'for adminuser', 'post.author_id adminuser.id =' );
         $ query -> andFilterWhere ([ 'like', 'adminuser.nickname', $ the this - > AUTHOR_NAME]); 


        // increase in the index field custom 
        $ the dataProvider -> Sort -> Attributes [ 'AUTHOR_NAME'] = [
             'asc' => ['adminuser.nickname'=>SORT_ASC],
            'desc' => ['adminuser.nickname'=>SORT_DESC],
        ];
        return $dataProvider;
    }
}

 

Guess you like

Origin www.cnblogs.com/gaogaoxingxing/p/12729587.html