yii2搜索链接到同一个表的两个字段

时间:2017-06-01 04:13:30

标签: php mysql yii2

我正在尝试在网格视图中实现搜索here。当您有一个与特定表有关系的单个字段时,此方法可以正常工作。但是,我有一个包含两个字段(resource_to_id,resource_from_id)的表,这两个字段与另一个表(资源)有关系。

在下面的型号代码中,我可以使用$ query-> joinwith line来搜索该字段,但不能同时搜索两者。如何实现两个资源字段的搜索?

<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Messages;

/**
 * MessagesSearch represents the model behind the search form about `app\models\Messages`.
 */
class MessagesSearch extends Messages
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'message_read'], 'integer'],
            [['subject', 'message', 'time_sent', 'resource_to_id', 'resource_from_id'], '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 = Messages::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;
        }

        $query->joinwith('resourceFrom');
        //$query->joinwith('resourceTo');

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'time_sent' => $this->time_sent,
            'message_read' => $this->message_read,
        ]);

        $query->andFilterWhere(['like', 'subject', $this->subject])
            ->andFilterWhere(['like', 'message', $this->message])
            ->andFilterWhere(['like', 'resources.resource_name', $this->resource_to_id])
            ->andFilterWhere(['like', 'resources.resource_name', $this->resource_from_id])
            ;

        return $dataProvider;
    }
}

1 个答案:

答案 0 :(得分:0)

在搜索功能中,您需要使用连接表的别名,如下所示:

$query->joinWith(['resourceFrom from', 'resourceTo to']);

然后修复andFilterWhere条件:

$query->andFilterWhere(['like', 'from.resource_name', $this->resource_from_id])
    ->andFilterWhere(['like', 'to.resource_name', $this->resource_to_id]);