M
M
Maxim Timofeev2016-06-06 19:52:32
MySQL
Maxim Timofeev, 2016-06-06 19:52:32

How to make a hasMany connection by two parameters?

there are 2 tables:
user (standard for yii advanced), id + other
user_relations fields in which id (PK), user_id, invite_id, type
you need to make a relationship that will select all user_relations, where either user_id or invite_id is equal to user-> id
try like this:

public function getFriendsList(){
        return $this->hasMany(UserRelation::className(),['user_id'=>'id'])->orWhere(['invite_id'=>$this->id]);
    }

there are no errors, but the sample is empty. I climb into the debug and see that my orWhere has turned into AND:
SELECT * FROM `user_relation` WHERE (`invite_id`=1) AND (`user_id`=1)

Am I sick or yii?
also tried like this:
public function getFriendsList(){
        return $this->hasMany(UserRalation::className(),['user_id'=>'id'])->orOnCondition(['invite_id'=>'id']);
    }

the result is identical

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Grabko, 2016-06-06
@VGrabko

At the moment, in my opinion, the problem is in yii. Run query builder for now

Дмитрий Ким, 2016-06-07
@kimono

https://github.com/yiisoft/yii2/blob/master/framew...
Попробуйте так:

public function getFriendsList(){
  return $this->hasMany(UserRelation::className(),['user_id'=>'id'])->where(['or', ['user_id' => $this->id],['invite_id'=>$this->id]);
}

А вообще уместнее будет:
public function getFriendsList(){
  return UserRelation::find()->where(['or', ['user_id' => $this->id],['invite_id'=>$this->id]);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question