php - Yii2 ActiveQuery 在链接数组中使用 OR

标签 php mysql activerecord yii2

我想在 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'
        ]);
    }

最佳答案

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

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

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

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

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

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

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

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

但不适用于$model->find()->with('transactions'),因为with需要设置$查询->链接。而 with 需要使用 join....

关于php - Yii2 ActiveQuery 在链接数组中使用 OR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26365150/

相关文章:

php - PHP MVC 框架中面向目标的设计

ruby-on-rails - 数据库分片和 Rails

ruby-on-rails - 如何在以文本形式存储在数据库中的 json 字段中使用 Activerecord 进行搜索

php - 如何在 symfony (Propel) 中加入一个表并通过一个查询从两个表中检索对象

php 在表单中显示信息

php - Opencart 从 php 文件中删除后显示产品数量

php - 使用列名从 MySQL 返回 JSON

mysql - 帮助调整 my.cnf 中的参数

mysql - 调整 SQL 行以包含集合

ruby - Rails 3 db :migrate 的未定义方法 `visitor'