A
A
akula222017-04-01 22:20:54
Yii
akula22, 2017-04-01 22:20:54

How to filter data under two fields from another table?

in the matches table there are two fields with the user ID, user1 and user2,
I need to filter in the grid by their name from the user table I
made two links

public function getUserHome()
    {
        return $this->hasOne(User::className(), ['id' => 'user1']);
    }

    public function getUserAway()
    {
        return $this->hasOne(User::className(), ['id' => 'user2']);
    }

further in the search model
public function rules()
    {
        return [
            [['id', 'status'], 'integer'],
            [['user1', 'user2', 'created_at'], 'safe'],
        ];
    }
$query = Matches::find()->with(['userHome', 'userAway', 'profileHome', 'profileAway'])->where(['tour_id' => $this->tourId]);

// grid filtering conditions
        $query->andFilterWhere([
            'FROM_UNIXTIME(created_at, "%d.%m.%Y")' => $this->created_at,
            'status' => $this->status,
        ]);


        $query->joinWith(
            [
                'userHome' => function ($q) {
                    $q->where('user.username LIKE "%' . $this->user1 . '%"');
                },
//                'userAway' => function ($q) {
//                    $q->where('user.username LIKE "%' . $this->user2 . '%"');
//                }
            ]
        );

this is how it works, user1 is filtered, if you uncomment it
//                'userAway' => function ($q) {
//                    $q->where('user.username LIKE "%' . $this->user2 . '%"');
//                }

then error
SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'user'
The SQL being executed was: SELECT COUNT(*) FROM `matches` LEFT JOIN `user` ON `matches`.`user1` = `user`.`id` LEFT JOIN `user` ON `matches`.`user2` = `user`.`id` WHERE (`tour_id`='26') AND (user.username LIKE "%vla%") AND (user.username LIKE "%%")

tell me how to fix it?

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
A
akula22, 2017-04-02
@akula22

Reading the documentation helped)
it was necessary like this

$query->joinWith(['userHome a' => function ($q) {
                    $q->where('a.username LIKE "%' . $this->user1 . '%"');
                }]);
        $query->joinWith(['userAway b' => function ($q) {
                $q->where('b.username LIKE "%' . $this->user2 . '%"');
            }]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question