簡體   English   中英

Yii2 ActiveQuery在鏈接數組中使用OR

[英]Yii2 ActiveQuery use OR in Link array

我想在ActiceRecord擴展的類中的hasMany函數中的$link數組中使用OR運算符。 例如,我想獲得與用戶帳戶相關的交易。 在sql中它會像SELECT * FROM transactions WHERE fromAccountId = :id OR toAccountId = :id但是我怎么能用Yii2寫這個

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

鏈接ActiveQuery使用數組的鍵作為名稱列,值 - 作為列的值。

對於此關系,數組鍵必須是表的列,並且數組值必須是主表中的相應列

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

[
    'fromAccountId' => 'id',
    'toAccountId' => 'id'
]

你可以在getTransactions()中重寫hasM​​any行為

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

它按預期支持本機行為:

$model->getTransactions() // return as \yii\db\ActiveQuery
$model->transactions // return as array of Transactions models

但不適用於工作$model->find()->with('transactions')因為with需要設置$query->link 相反, with必要使用join....

你可以使用find(),它不是很好,但做的工作:

return $this->find()->join('LEFT JOIN', 'transaction', 'fromAccountId = id OR toAccountId = id')->all();

也許你必須使用tablename.id!

我沒有試過這個,但你可以嘗試類似的東西

public function getTransactions() {
        return $this->hasMany(Transaction::className(), ['1' => '1'])->where('fromAccountId = id OR toAccountId = id');
    }

我們的想法是創建一個沒有條件(或具有虛擬條件)的連接,然后使用where來獲得所需的實際結果。 這可能意味着一個巨大的性能問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM