Yii2 Working with Relational Data at ActiveDataProvider

Yii2 Working with Relational Data at ActiveDataProvider

namespace common\models;

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

/**
 * RecordingSearch represents the model behind the search form about `common\models\Recording`.
 */
class RecordingSearch extends Recording
{
    public $integerReg = '/^\s*[+-]?\d+\s*$/';
    
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['book_id'], 'integerAndString'],
        ];
    }
    
    public function integerAndString($attribute, $params)
    {
        if (!preg_match($this->integerReg, $this->$attribute) && !is_string($this->$attribute)) {
            $this->addError($attribute, Yii::t('yii', '{attribute} must be an integer or a string.', ['attribute'=>$this->getAttributeLabel($attribute)]));
        }
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        // ......
        
        if (empty($this->book_id) || preg_match($this->integerReg, $this->book_id)) {
            $query->andFilterWhere(['book_id' => $this->book_id]);
        } else {
            $query->joinWith('book')->andFilterWhere(['like', Book::tableName().'.name', $this->book_id]);
        }

        // ......
    }
}

 

posted on 2015-03-09 09:58  技术员  阅读(833)  评论(2编辑  收藏  举报

导航