19
Окт
2021

yii2, GridView, searchModel , поиск по связанным моделям

action в контроллере

 public function actionIndex()
    {
        $model = new VacanciesFilter();
        $dataProvider = $model->search(\Yii::$app->request->queryParams);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'searchModel' => $model,
        ]);
    }

Модель Vacancies

<?php

namespace common\models;

/**
 * This is the model class for table "vacancies".
 *
 * @property int $id
 * @property int $employer_id
 * @property int $specialization
 * @property int $country
 * @property string $wage
 * @property string $description
 * @property int|null $employer_type
 *
 * @property EmployerUsers $employer
 * @property EmploymentType $employerType
 * @property Specializations $specialization0
 */
class Vacancies extends \yii\db\ActiveRecord
{

    public $hiddenCountry;
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'vacancies';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['employer_id', 'specialization', 'country', 'wage', 'description'], 'required'],
            [['employer_id', 'specialization', 'employer_type', 'wage', 'hiddenCountry'], 'integer'],
            [['description', 'country'], 'string'],
            [['specialization'], 'exist', 'skipOnError' => true, 'targetClass' => Specializations::className(), 'targetAttribute' => ['specialization' => 'id']],
            [['employer_id'], 'exist', 'skipOnError' => true, 'targetClass' => EmployerUsers::className(), 'targetAttribute' => ['employer_id' => 'id']],
            [['employer_type'], 'exist', 'skipOnError' => true, 'targetClass' => EmploymentType::className(), 'targetAttribute' => ['employer_type' => 'id']],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'employer_id' => 'Employer',
            'specialization' => 'Specialization',
            'country' => 'Country',
            'wage' => 'За зарплатою',
            'date' => 'За датою',
            'description' => 'Description',
            'employer_type' => 'Employer Type',
        ];
    }

    /**
     * Gets query for [[Employer]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getEmployer()
    {
        return $this->hasOne(EmployerUsers::className(), ['id' => 'employer_id']);
    }

    /**
     * Gets query for [[EmployerType]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getEmployerType()
    {
        return $this->hasOne(EmploymentType::className(), ['id' => 'employer_type']);
    }

    public function getCountry()
    {
        return $this->hasOne(Locality::className(), ['id' => 'country']);
    }

    public function getCountryName()
    {
        return $this->hasOne(Locality::className(), ['id' => 'country']);
    }

    /**
     * Gets query for [[Specialization0]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getSpecializations()
    {
        return $this->hasOne(Specializations::className(), ['id' => 'specialization']);
    }

    public function getUser()
    {
        return $this->hasOne(EmployerUsers::className(), ['id' => 'employer_id'])->joinWith('user');
    }
}

Модель VacanciesSearch

<?php

namespace backend\models;

use common\models\Vacancies;
use yii\data\ActiveDataProvider;

class VacanciesFilter extends Vacancies
{
    public $employer_id;

    public function rules()
    {
        return [
            ['employer_id', 'safe']
        ];
    }

    public function search($params)
    {

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

        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }

        $query->leftJoin('employer_users')->where(['like', 'employer_users.company_name', $params['VacanciesFilter']['employer_id']]);

        return $dataProvider;
    }
}

GridView

 <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'id',
            [
                'attribute' => 'employer_id',
                'value' => function ($model) {
                    return $model->employer->company_name;
                },
            ],
            [
                'attribute' => 'specialization',
                'value' => function ($model) {
                    return $model->specializations->name;
                },
            ],
            [
                'attribute' => 'country',
                'value' => function ($model) {
                    return $model->countryName->title . ' ' . $model->countryName->type;
                },
            ],
            'wage',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>

введите сюда описание изображения

Результат

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

Как правильно реализовать связку?

Источник: https://ru.stackoverflow.com/questions/1339811/yii2-gridview-searchmodel-%D0%BF%D0%BE%D0%B8%D1%81%D0%BA-%D0%BF%D0%BE-%D1%81%D0%B2%D1%8F%D0%B7%D0%B0%D0%BD%D0%BD%D1%8B%D0%BC-%D0%BC%D0%BE%D0%B4%D0%B5%D0%BB%D1%8F%D0%BC

Тебе может это понравится...

Добавить комментарий