M
M
MCFlower2017-02-17 09:50:32
Yii
MCFlower, 2017-02-17 09:50:32

Yii2 how to write a condition for a linked table?

Good afternoon.
I've been fighting for a day now.
We have a table model Video2user which stores user_id and video_id. There is also a Video table model in which there are id, code, party fields.
It is required to get the Code from the video base through Active Record where, for example, party = 2.
If on pure sql, then it looks like this

select v.code 
from video2user v2u, video v 
where v2u.video_id = v.id 
and v.party = 2 
and v2u.user_id = :user_id                
order by v2u.video_id

So everything works, but why exactly Active Record - because I use the resulting model in the Pagination class.
So what am I doing. In the Video2user model, I create a connection with the Video model
public function getVideo(){
     return $this->hasOne(Video::className(), ['id' => 'video_id'])->where(['party' => 2]);
}

And in the controller I call
$query2 = Video2user::find()->where(['user_id' => 5555])->with('video')->all();

All data on this user id is returned to me, the only thing is just where party = 2 - a second-level array is added. And it is necessary that only those records where party = 2 and nothing more are selected. To make it convenient to work with Pagination.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitrij, 2017-02-17
@MCFlower

Something like
?
Accordingly, this alias can also be used in ->select('j.id').

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question