Поиск и фильтр gridview по нескольким таблицам РЕШЕНО

Общие вопросы по использованию второй версии фреймворка. Если не знаете как что-то сделать и это про Yii 2, вам сюда.
Ответить
Аватара пользователя
svil
Сообщения: 563
Зарегистрирован: 2018.02.12, 22:41

Поиск и фильтр gridview по нескольким таблицам РЕШЕНО

Сообщение svil »

Таблица group связана с product

Код: Выделить всё

public function getProducts()
    {
        return $this->hasMany(Product::className(), ['group_id' => 'id']);
    }
Таблица product связана с offer

Код: Выделить всё

 public function getOffers()
    {
        return $this->hasMany(Offer::className(), ['product_id' => 'id']);
    }
Как в gridview сделать поиск по полю group в offer/index это groupName
Пока выводит ошибку что не находит groupName
вид offer/index

Код: Выделить всё

<?php


use yii\helpers\Html;
use yii\grid\GridView;

/* @var $this yii\web\View */
/* @var $searchModel app\modules\admin\models\OfferSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Offers';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="offer-index">

    <h1><?= Html::encode($this->title) ?></h1>
    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

    <p>
        <?= Html::a('Create Offer', ['create'], ['class' => 'btn btn-success']) ?>
    </p>

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

            'id',
            'name',
            'accounting_id',
            'product_id',
            [
                'attribute' => 'groupName',
                'value' => function($data){
                    return $data->product->group->name;
                },
            ],
            'remnant',
            'is_active',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>
</div>
OfferSearch

Код: Выделить всё

<?php

namespace app\modules\admin\models;

use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\modules\admin\models\offer;
use app\modules\admin\models\group;
use app\modules\admin\models\product;

/**
 * OfferSearch represents the model behind the search form of `app\modules\admin\models\offer`.
 */
class OfferSearch extends offer
{
    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['id', 'product_id', 'is_active'], 'integer'],
            [['name', 'accounting_id'], 'safe'],
            [['remnant'], 'number'],
            [['groupName'], '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 = offer::find();

        // add conditions that should always apply here

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

        $this->load($params);

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

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'product_id' => $this->product_id,
            'groupName' => [
                'asc' => ['group.name' => SORT_ASC],
                'desc' => ['group.name' => SORT_DESC],
                'label' => 'Группа'
            ],

            'remnant' => $this->remnant,
            'is_active' => $this->is_active,
        ]);


        $this->load($params);

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


      $query->andFilterWhere([
            'offer.id' => $this->id,
            'offer.product_id' => $this->product_id,
            'offer.accounting_id' => $this->accounting_id,
            'offer.name' => $this->name,

        ]);


        $query->andFilterWhere([
            'or',
            ['like', 'offer.name', $this->name],
            ['like', 'offer.accounting_id', $this->accounting_id],
        ]);





        $query->andFilterWhere(
            ['group.id' => 'product.group_id'])

        ->viaTable(
            'group',
            ['id' => 'product.group_id'],
            function ($query) {
                $query->andWhere([

                    'or',
        ['like', 'group.name',  "%' . $this->groupName . '%"],

                ]);
            }
        );



      //  return $this->hasOne(Companies::className(), ['id' => 'id_company'])->viaTable('contacts', ['id' => 'contracts_id']);



        return $dataProvider;
    }
}
Последний раз редактировалось svil 2019.05.20, 22:39, всего редактировалось 3 раза.
Аватара пользователя
svil
Сообщения: 563
Зарегистрирован: 2018.02.12, 22:41

Re: Поиск и фильтр gridview по нескольким таблицам

Сообщение svil »

Методом тыка заработало
Модель Search

Код: Выделить всё

<?php

namespace app\modules\admin\models;

use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\modules\admin\models\Offer;

/**
 * OfferSearch represents the model behind the search form of `app\modules\admin\models\Offer`.
 */
class OfferSearch extends Offer
{
    public $groupName;
    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['id', 'product_id', 'is_active'], 'integer'],
            [['name', 'accounting_id', 'groupName'], 'safe'],
            [['remnant'], 'number'],
        ];
    }

    /**
     * {@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 = Offer::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'sort' => ['attributes' => ['id', 'product_id', 'is_active','name', 'accounting_id',

                'groupName' => [
                    'asc' => ['group.name' => SORT_ASC],
                    'desc' => ['group.name' => SORT_DESC],
                    'label' => 'Группа'
                ],

                ]]
        ]);


        $this->load($params);

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

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'product_id' => $this->product_id,
            'remnant' => $this->remnant,
            'is_active' => $this->is_active,
        ]);

        $query->andFilterWhere(['like', 'name', $this->name])
            ->andFilterWhere(['like', 'accounting_id', $this->accounting_id]);

        $query->joinWith(['group' => function ($q) {
            $q->where('group.name LIKE "%' .  $this->groupName . '%"');
        }]);

        return $dataProvider;
    }
}
Модель Offer

Код: Выделить всё

public function getProduct()
    {
        return $this->hasOne(Product::className(), ['id' => 'product_id'])->with(['group']);
    }

    public function getGroup()
    {
        return $this->hasOne(Group::className(), ['id' => 'group_id'])
            ->viaTable(
                'product',
                ['id' => 'product_id']
            );
    }
    

    /* Геттер для наименования группы
     */
    public function getGroupName() {
        return $this->Group->name;
    }


Модель Group

Код: Выделить всё

public function getOffer() {

        return $this->hasMany(Offer::className(), ['id' => 'product_id'])
            ->viaTable(
                'product',
                ['group_id' => 'group.id'],
                function ($query) {
                    $query->andWhere(['offer.product_id' => 'product.id']);
                });
    }
Вид offer/index

Код: Выделить всё

<?php

use yii\helpers\Html;
use yii\grid\GridView;

/* @var $this yii\web\View */
/* @var $searchModel app\modules\admin\models\OfferSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Offers';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="offer-index">

    <h1><?= Html::encode($this->title) ?></h1>
    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

    <p>
        <?= Html::a('Create Offer', ['create'], ['class' => 'btn btn-success']) ?>
    </p>

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

            'id',
            'name',
            'accounting_id',
            'product_id',
            [
               'attribute' => 'groupName',
                'value' => function($data){
                    return $data->product->group->name;
                },
            ],

      'remnant',
            'is_active',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>
</div>
Ответить