Home >Backend Development >PHP Tutorial >The problem of getting the sum of a certain field in yii2 framework sql
Is there a SQL sum method in the yii2 framework that can directly query the sum of a certain field based on SQL conditions? For example, I want to get the commentNum field and value of type='isOpen' in my db_article_list article table! Or if you write sql yourself, how to execute customized sql through the framework!
Is there a SQL sum method in the yii2 framework that can directly query the sum of a certain field based on SQL conditions? For example, I want to get the commentNum field and value of type='isOpen' in my db_article_list article table! Or if you write sql yourself, how to execute customized sql through the framework!
It is still convenient to execute the sql
written by yourself. The following is an example of executing the customized sql
. Please take a look
<code>$sql = "SELECT SUM(commentNum) AS num FROM db_article_list WHERE `type`='isOpen'"; $commentNum = Yii::$app->db->createCommand($sql)->queryOne();</code>
Just change the selection
$model->find()->select(['num'=>'SUM(commentNum)'])->where(['type'=>'isOpen'])-> one();
Of course there is a sum
method!
Query
<code>(new Query())->from('table')->sum('field');</code>
AR
<code>Article::find()->sum('field');</code>