Yii2 ActiveQuery在Link数组中使用OR

Бог*_*нко 5 php mysql activerecord yii2

我想 在ActiceRecord扩展的类的函数中的$link数组中使用OR运算符hasMany。例如,我要获取与用户帐户相关的交易。在SQL中这将是类似的东西,SELECT * FROM transactions WHERE fromAccountId = :id OR toAccountId = :id但是我如何使用Yii2写这个

    public function getTransactions() {
        return $this->hasMany(Transaction::className(), [
            'fromAccountId' => 'id',
            'toAccountId' => 'id'
        ]);
    }
Run Code Online (Sandbox Code Playgroud)

Evg*_*nko 4

Link ActiveQuery 使用数组的键作为名称列,使用值作为列的值。

数组键必须是该关系的表的列,数组值必须是主表中的相应列

因为代码不起作用(where (fromAccountId, toAccountId) IN ('id','id')):

[
    'fromAccountId' => 'id',
    'toAccountId' => 'id'
]
Run Code Online (Sandbox Code Playgroud)

您可以重写 getTransactions() 中的 hasMany 行为

public function getTransactions() {
    $query = Transaction::find();
    $query->multiple = true;
    return $query->where(['OR',
        ['fromAccountId' => $this->id],
        ['toAccountId' => $this->id]
    ]);
}
Run Code Online (Sandbox Code Playgroud)

正如预期的那样,它支持本机行为:

$model->getTransactions() // return as \yii\db\ActiveQuery
$model->transactions // return as array of Transactions models
Run Code Online (Sandbox Code Playgroud)

但不起作用$model->find()->with('transactions'),因为with需要设置$query->link。相反with需要使用join....