2

связанные поля я вывел: http://joxi.ru/a2XOvoWi197WPm но если пробовать поиск по ним, то получаю ошибку вида: http://joxi.ru/xAe5VWYipvZ4WA

модель - DishSearch.php:

<?php

namespace common\models;

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

/**
 * DishSearch represents the model behind the search form about `common\models\Dish`.
 */
class DishSearch extends Dish
{
    /* вычисляемый атрибут */
    public $categoryNameRu;
    public $categoryNameEn;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'weight', 'category_id', 'status'], 'integer'],
            [['title_ru', 'title_en', 'desc_ru', 'desc_en', 'url', 'img_url', 'categoryNameRu', 'categoryNameEn'], '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 = Dish::find();

        // add conditions that should always apply here

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

        if (!($this->load($params) && $this->validate())) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
          $query->joinWith(['category']);
            return $dataProvider;
        }

        $this->addCondition($query, 'title_ru');
        $this->addCondition($query, 'title_en');

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'weight' => $this->weight,
            'category_id' => $this->category_id,
            'status' => $this->status,
        ]);

        $query->andFilterWhere(['like', 'title_ru', $this->title_ru])
            ->andFilterWhere(['like', 'title_en', $this->title_en])
            ->andFilterWhere(['like', 'desc_ru', $this->desc_ru])
            ->andFilterWhere(['like', 'desc_en', $this->desc_en])
            ->andFilterWhere(['like', 'url', $this->url])
            ->andFilterWhere(['like', 'img_url', $this->img_url]);

        $query->joinWith(['category' => function ($q) {
            //$q->andFilterWhere(['like', 'tbl_category.title_ru', $this->categoryNameRu]);
          //$q->andFilterWhere(['like', 'tbl_category.title_en', $this->categoryNameEn]);
          $q->where('tbl_category.title_ru LIKE "%' . $this->categoryNameRu . '%"');
          $q->where('tbl_category.title_ru LIKE "%' . $this->categoryNameEn . '%"');
        }]);

        return $dataProvider;
    }
}

модель Dish.php

<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "dish".
 *
 * @property integer $id
 * @property string $title_ru
 * @property string $title_en
 * @property string $desc_ru
 * @property string $desc_en
 * @property string $url
 * @property string $img_url
 * @property integer $weight
 * @property integer $category_id
 * @property integer $status
 *
 * @property Category $category
 */
class Dish extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'dish';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title_ru', 'title_en', 'category_id'], 'required'],
            [['weight', 'category_id', 'status'], 'integer'],
            [['weight'], 'integer', 'max' => 300, 'min' => -300],
            [['title_ru', 'title_en', 'desc_ru', 'desc_en', 'url', 'img_url'], 'string', 'max' => 255],
            [['category_id'], 'exist', 'skipOnError' => true, 'targetClass' => Category::className(), 'targetAttribute' => ['category_id' => 'id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title_ru' => 'Title Ru',
            'title_en' => 'Title En',
            'desc_ru' => 'Desc Ru',
            'desc_en' => 'Desc En',
            'url' => 'Url',
            'img_url' => 'Img Url',
            'weight' => 'Weight',
            'category_id' => 'Category ID',
            'categoryNameRu' => 'Category Name (RU)',
            'categoryNameEn' => 'Category Name (EN)',
            'status' => 'Status',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    /* Связь с моделью Category*/
    public function getCategory()
    {
        return $this->hasOne(Category::className(), ['id' => 'category_id']);
    }

    /* Геттер для названия категории */
    public function getCategoryNameRu() {
        return $this->category->title_ru;
    }

    /* Геттер для названия категории */
    public function getCategoryNameEn() {
        return $this->category->title_en;
    }
}

не могу понять почему поиск не работает, вроде сами поля выводятся и значения правильные самих категорий

1 ответ 1

0

Ругается ведь на метод addCondition значит не используйте его. Попробуйте сделать поиск в DishSearch.php через andFilterWhere как там ниже.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.