SearchModel.php 1.52 KB
<?php
    /**
     * Created by PhpStorm.
     * User: stes
     * Date: 22.06.18
     * Time: 12:40
     */
    
    namespace frontend\models;
    
    use common\models\Book;
    use yii\base\Model;
    use yii\db\Expression;
    use yii\db\Query;
    use yii\web\JsExpression;

    class SearchModel extends Model
    {
        public $text;
        
        public $author;
        
        public $bookTitle;
        
        public function rules()
        {
            return [
                [
                    'text',
                    'required',
                    'whenClient' => new JsExpression('function (attribute, value) {
                        return $("#next").data("id") == "";
                    }'),
                ],
                [
                    ['author', 'bookTitle'],
                    'boolean'
                ],
                [
                    'text', 'string'
                ]
            ];
        }
        
        public function search(){
            $query = (new Query())->select('book.id')->from('book')->join('INNER JOIN', 'author', 'book.author_id = author.id');
            if ($this->author){
                $query->where(['ilike', 'book.title', $this->text]);
            }
            if ($this->bookTitle){
                $query->orWhere(['ilike', 'secondname', $this->text])->orWhere(['ilike', new Expression('concat(name,\' \',secondname)'), $this->text]);
            }
            return $query->andWhere(['book.status' => Book::STATUS_ACTIVE])->column();
        }
    }