【问题标题】:Yii2 ActiveQuery use OR in Link arrayYii2 ActiveQuery 在链接数组中使用 OR
【发布时间】:2014-10-14 15:59:37
【问题描述】:

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

【问题讨论】:

    标签: php mysql activerecord yii2


    【解决方案1】:

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

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

    因为代码不起作用(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]
        ]);
    }
    

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

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

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

    【讨论】:

      【解决方案2】:

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

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

      也许你必须使用 tablename.id!

      【讨论】:

        【解决方案3】:

        这个我没试过,你可以试试

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

        这个想法是创建一个不带条件(或带有虚拟条件)的连接,然后使用 where 来获得您想要的实际结果。这可能意味着严重的性能问题。

        【讨论】:

        • ['1' => '1'] 获取未知属性:Model::1
        • 获取未知属性:模型 ::1
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多