Как мне отфильтровать экземпляры модели по их виртуальному атрибуту в модели yii2 с помощью ActiveDataProvider? - PullRequest
0 голосов
/ 07 августа 2020

У меня есть класс продукта, и он содержит два атрибута 'price' и 'sale_price', а также у меня есть получатель getOriginalPrice.

/**
 * This is the base model class for table "product".
 *
 * more attribute here..
 * @property float $price
 * @property float|null $sale_price
 * more attribute here...
 */
class Product extends \yii\db\ActiveRecord
{
    /**
     * get product original price 
     * 
     * @return float
     */
    public function getOriginalPrice()
    {
        if(!is_null($this->sale_price) && (float)$this->sale_price > 0)
        {
            return $this->sale_price;
        }

        return $this->price; 
    }

}

, поэтому мой вопрос в том, как я могу фильтровать модель продукта в отношении этого виртуального атрибута originalprice?

я попытался отфильтровать модель, используя product/index?sort=originalprice и product/index?sort=-originalprice в URL-адресе, и поместить этот код в модель ProductSearch, но безуспешно.

$query = Product::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query
        ]);
        
        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

      
        //filtering conditions
        $query->andFilterWhere([
            'price' => $this->price,
            'originalprice' => $this->originalprice,
            'product_cat_id' => $this->product_cat_id,
        ]);


        $query->andFilterWhere(['like', 'name', $this->name]);

        return $dataProvider;

кто-нибудь знает, как его решить?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...