Activerecord Findbysql Exception

I’m newbie in Yii2. But I decided to start with Yii2.

I wanted to use the method "findBySQL" in my model. The SQL has the aggregation function "MAX" in the select Statement. see:




   $sql = 'SELECT MAX(' . $keyName . ') from ' . $this->tableName();

   // 'Select MAX(rcv_Id) from Table'

   $row[] = $this->findBySQL($sql)->one();



The reply is an exception:





Unknown Property – yii\base\UnknownPropertyException


Setting unknown property: app\models\GenericCodeValue::MAX(rcv_id)


1. in C:\xampp\htdocs\yii2\TestApp\vendor\yiisoft\yii2\yii\base\Component.php at line 116 

            }

        }

        if (method_exists($this, 'get' . $name)) {

            throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);

        } else {

            throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);

        }

    }

 

    /**

     * Checks if a property value is null.



It seems that ActiveQuery::one expect an Attribute ‘MAX(rcv_id)’ in my model which isn’t the case. Aggregated attributes shouldn’t be used for further Actions.

I will use ActiveQuery directly.

this should work:




   $row[] = $this->find()->max($keyName);



in general when selecting something like MAX() you should write MAX(…) AS attrName and have an attribute or public property in your AR class with that name.