1
votes

Is that possible to use variable in the onCondition?

Here is the relation:

public function getMybook()
{
    return $this->hasOne(Book::className(), ['book_id' => 'idbook'])->onCondition(['user_id' => $user_id]);
}

I want to use it in joinWith like below:

$books = Books::find()->joinWith('myBook')->all();

But how do I send the user_id parameter into the onConditon? Thanks!

2

2 Answers

3
votes

You may use closure, for example:

return $this->hasOne(Book::className(), ['book_id' => 'idbook'])->andWhere('user_id = :user_id');


$user_id = 123;
$books = Books::find()->joinWith([
    'myBook' => function ($q) use ($user_id) {
        $q->addParams([':user_id' => $user_id]);
    }
])->all();
0
votes

Can not use dynamic param in relation function.
But why don't you use where condition:

$books = Books::find()->joinWith('myBook')->where(['myBook.user_id'=>$user_id])->all();