Switch88
Switch88

Reputation: 130

YIi2 - comparing two field in searchModel

I have a table called TPurchasing which contain data about a store's purchasing record.

TPurchasing

By using gii feature in yii2, I manage to generate a model called TPurchasingSearch from "CRUD Generator" menu. In the TPurchasingSearch, there is a function called search() which is used by the GridView in the view file.

public function search($params)
{
    $query = TPurchasing::find();
    $dataProvider = new ActiveDataProvider([
        'pagination' => ['pageSize' => 20],
        'query' => $query,
        'sort' => ['defaultOrder' => ['transaction_time' => SORT_DESC]]
    ]);

    $this->load($params);

    if (!$this->validate()) {
        $query->where('0=1');
        return $dataProvider;
    }

    $query->andFilterWhere(['is_removed' => 0]);
    $query->andFilterWhere(['like', 'supplier_name', $this->supplier_name])
        ->andFilterWhere(['like', 'payment_type', $this->payment_type])
        ->andFilterWhere(['>', 'total', 'paid']);

    return $dataProvider;
}

Right now I'm trying to display records that is still not totally paid off, which means the "paid" column is smaller than "total" column. How can I do this comparison in the search function? The above code gave me an error:

invalid input syntax for type double precision: "paid"

on this part

->andFilterWhere(['>', 'total', 'paid']);

since it tried to compare total column with string "paid". I might missed it, but I can't seem to find the related answer in Yii2 documentation.

Upvotes: 0

Views: 600

Answers (1)

soju
soju

Reputation: 25312

No need to use andFilterWhere() here, you could simply try :

 $query->andWhere('total > paid');

Upvotes: 2

Related Questions