A
A
Alexey2014-07-07 17:17:52
Yii
Alexey, 2014-07-07 17:17:52

How to work with linked tables in Yii2?

I have tables:
User
(id, name, surname)
and
UserContacts
(u_id1, u_id2).
Action in the model:
(Does not work)
return $this->hasMany(User::className(), ['id' => 'u_id1', 'id' => 'u_id2'])
->viaTable('UserContacts', ['id' => 'u_id1', 'id' => 'u_id2']);
Tell me how can I get a linked table, where each u_id1 = id (from the User table), u_id2 = id (from the User table), with a single query using viaTable ()?
And then get all the data.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dmitry Entelis, 2014-07-07
@DmitriyEntelis

habrahabr.ru/post/226103

A
Alexander Zelenin, 2014-07-07
@zelenin

public function getAttrs()
    {
        return $this
            ->hasMany(Profile::className(), ['user_id' => 'id'])
            ->where('name = "name"')->union(
                $this->hasMany(Profile::className(), ['user_id' => 'id'])->where('name = "surname"')
            );
    }

here is a working option.
return $this->hasMany(User::className(), ['id' => 'u_id1'])
->viaTable('UserContacts', ['id' => 'u_id1'])->union($this->hasMany(User::className(), ['id' => 'u_id2'])
->viaTable('UserContacts', ['id' => 'u_id2']));

more or less like this.

A
Alexey, 2014-07-08
@azovl

return $this->hasMany(User::className(), ['id' => 'u_id2'])
->viaTable(UserContact::tableName(), ['u_id1' => 'id']);

The only question left is how to add the 'where' condition to the viaTable. Ie it is necessary to find, for example, with type = 1, only in the UserContact table?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question