SearchForm.php 2.65 KB
<?php
    
    namespace common\models;
    
    use artbox\catalog\models\Category;
    use artbox\catalog\models\Product;
    use yii\base\Model;
    use yii\db\ActiveQuery;
    
    /**
     * Class SearchForm for performing search around site.
     */
    class SearchForm extends Model
    {
        /**
         * @var string $word
         */
        public $word;
        
        /**
         * @inheritdoc
         */
        public function rules()
        {
            return [
                [
                    [ 'word' ],
                    'required',
                    'message' => \Yii::t('app', 'Write text to search for.'),
                ],
                [
                    [ 'word' ],
                    'string',
                    'min'      => 3,
                    'message'  => \Yii::t('app', 'Write at least 3 symbols.'),
                    'tooShort' => \Yii::t('app', 'Write at least 3 symbols.'),
                ],
            ];
        }
        
        /**
         * @inheritdoc
         */
        public function attributeLabels()
        {
            return [
                'word' => \Yii::t('app', 'Поиск по сайту'),
            ];
        }
        
        public function search()
        {
            return Product::find()
                          ->joinWith('lang')
                          ->joinWith('variants.lang')
                          ->andWhere(
                              [
                                  'product.status' => true,
                                  'variant.status' => true,
                              ]
                          )
                          ->andWhere(
                              [
                                  'ilike',
                                  'product_lang.title',
                                  $this->word,
                              ]
                          )
                          ->orWhere(
                              [
                                  'ilike',
                                  'variant_lang.title',
                                  $this->word,
                              ]
                          )
                          ->orWhere([ 'variant.sku' => $this->word ])
                          ->groupBy('product.id');
        }
        
        public function searchCategory(Category $category, ActiveQuery $query)
        {
            return $query->joinWith('productToCategories')
                         ->andWhere(
                             [
                                 'product_to_category.category_id' => $category->id,
                             ]
                         );
        }
    }