I want to use OR operator in $link
array in hasMany
function in class extended by ActiceRecord.
For example, I want to get transactions which related whith user account. In sql it would be something like SELECT * FROM transactions WHERE fromAccountId = :id OR toAccountId = :id
But how I can wrote this using Yii2
public function getTransactions() {
return $this->hasMany(Transaction::className(), [
'fromAccountId' => 'id',
'toAccountId' => 'id'
]);
}
Link ActiveQuery works with the keys of the array as name column, values - as value of column.
The array keys must be columns of the table for this relation, and the array values must be the corresponding columns from the primary table
Because the code doesn't work (where (fromAccountId, toAccountId) IN ('id','id')
):
[
'fromAccountId' => 'id',
'toAccountId' => 'id'
]
You can rewrite hasMany behavior in getTransactions()
public function getTransactions() {
$query = Transaction::find();
$query->multiple = true;
return $query->where(['OR',
['fromAccountId' => $this->id],
['toAccountId' => $this->id]
]);
}
It supports native behavior, as expected:
$model->getTransactions() // return as \yii\db\ActiveQuery
$model->transactions // return as array of Transactions models
But doesn't work for $model->find()->with('transactions')
, because with
require setting $query->link
. Instead with
need to use join....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With