Home >Backend Development >PHP Tutorial >The problem of getting the sum of a certain field in yii2 framework sql

The problem of getting the sum of a certain field in yii2 framework sql

WBOY
WBOYOriginal
2016-08-18 09:16:271700browse

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!

Reply content:

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!

  1. Query

<code>(new Query())->from('table')->sum('field');</code>
  1. AR

<code>Article::find()->sum('field');</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn