M
M
Maxim2018-05-24 22:52:51
Yii
Maxim, 2018-05-24 22:52:51

Yii Active Query - How to make a selection of the same type of values?

Hello! I have a linking table of user and dialog:

$this->createTable('user_dialog', [
            'user_id' => $this->integer(),//Пользователь
            'dialog_id' => $this->integer(),//Доступ к диалогу
            'deleted' => $this->smallInteger(1)->notNull()->defaultValue(0),//Скрыть диалог от пользователя (удалить)
            'PRIMARY KEY(user_id, dialog_id)',
        ]);

I need to check for the existence of a dialogue between two users with ONE query to the database. Prompt the correct request from basis. I do like this:
$userDialog = UserDialog::find()
                ->where(['user_id' => [$currentUserID, $from_id]])
                ->asArray()
                ->all();

However, with this approach, I get all the dialogs of these users. And you only need to display only their dialogue, and not all.
Sample data in the
user_id table | dialog_id | deteled
1 | 1 | 0
2 | 1 | 0
1 | 2 | 0
3 | 2 | 0
The current selection for the query above is as follows:
array(3) {
  [0]=>
  array(3) {
    ["user_id"]=>
    string(1) "1"
    ["dialog_id"]=>
    string(2) "1"
    ["deleted"]=>
    string(1) "0"
  }
  [1]=>
  array(3) {
    ["user_id"]=>
    string(1) "1"
    ["dialog_id"]=>
    string(2) "2"
    ["deleted"]=>
    string(1) "0"
  }
  [2]=>
  array(3) {
    ["user_id"]=>
    string(1) "2"
    ["dialog_id"]=>
    string(2) "1"
    ["deleted"]=>
    string(1) "0"
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anatoly Medvedev, 2018-05-25
@myks92

I'm not strong in SQL, but in theory it should work like this:

SELECT a.dialog_id FROM user_dialog as a INNER JOIN user_dialog as b on a.dialog_id = b.dialog_id WHERE a.user_id = 1 AND b.user_id = 2;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question