5

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

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

0

You can use the find(), it's not as nice, but do the work:

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

Maybe you have to use tablename.id!

Comments

-2

I have not tried this, but you could try something like

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

The idea is to create a join without a condition (or with a dummy condition) then use where to get the actual results you want. This might mean a massive performance problem.

2 Comments

['1' => '1'] Getting unknown property: Model::1
Getting unknown property : Model ::1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.