Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 ActiveQuery use OR in Link array

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'
        ]);
    }
like image 492
Богдан Горбатенко Avatar asked Oct 31 '22 15:10

Богдан Горбатенко


1 Answers

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....

like image 130
Evgeniy Tkachenko Avatar answered Nov 15 '22 04:11

Evgeniy Tkachenko