code-zoop
code-zoop

Reputation: 7368

Calculate 2 columns together in Yii2 model::find() function

I have the following working find() function in Yii2:

User::find()->select('id, name')->where(['status' => '10'])->all()

However, the User model also has the following attributes:

'credit'
'ammount'

I need to check if the 'ammount' minus 'credit' is more that a value ($price) I am passing to the function.

How can I make a User:find() query where I am only getting the user objects where the amount minus credit is larger than the value I am checking against?

Thanks

Upvotes: 0

Views: 443

Answers (1)

Muhammad Omer Aslam
Muhammad Omer Aslam

Reputation: 23738

I assume the amount and credit are in the user table so you can do something like.

User::find()->select([new \yii\db\Expression('id,amount,credit')])
->where(['status' => '10'])
->andWhere('amount - credit > :yourAmount',[':yourAmount'=>$price])
->all();

or use addParams() to bind the custom value

User::find()->select([new \yii\db\Expression('id,amount,credit')])
->where(['status' => '10'])
->andWhere('amount - credit > :yourAmount')
->addParams([':yourAmount'=>$price])
->all();

Upvotes: 1

Related Questions