简体   繁体   中英

Yii : how to count records in a model?

I have following code to fetch data from a model.

$notifyModel = Notification::model()->findByAttributes(array(
                  'user_id'=> Yii::app()->user->uid
               ));

Now I want to count the number of rows fetched. Neither $notifyModel->count() work nor count($notifyModel) . It is very simple but googling did not help.

$notifyModels = Notification::model()->findAllByAttributes(array(
            'user_id'=> Yii::app()->user->uid
        ));

$count = count($notifyModels);

Or

$count = Notification::model()->countByAttributes(array(
            'user_id'=> Yii::app()->user->uid
        ));

the right usage of count():


    $userid =  Yii::app()->user->uid;
    $count = Notification::model()->count( 'user_id=:userid', array(':userid' => $userid));

Please see http://www.yiiframework.com/doc/api/1.1/CActiveRecord#count-detail

try this:

$userid =  Yii::app()->user->uid;

$notifyModel = Notification::model()->count(
           array('condition' => 'user_id=:userid', 
                 'params'=>array(':userid' => $userid)
                ));
$count = Notification::model()->countByAttributes(array( 'user_id'=> Yii::app()->user->uid ));

Since the questions title is about calling the count function in a model I'll add some for those beginners reading this :)

A function inside a model could look like this:

/**
 * Count the number of rows which match the user ID
 * @param int $uid The user ID
 * @return int The number of found rows
 */
public function getCountByUserID($uid)
{
    $count = $this->count(array(
        'condition'=>'user_id = :uid',
        'params'=>array(
            ':uid'=>$uid,
        ),
    ));
    return $count;
}

simple ways:

$model = News::model()->findAll(); //returns AR objects
         $count = count($model);

I think it is much faster than others

$userTable=User::model()->tableName();
$userid =  Yii::app()->user->uid;
$criteria=new CDbCriteria();
$criteria->select=count(id);
$criteria->compare('user_id',$userid);
$count=Yii::app()->db->commandBuilder->createFindCommand($userTable,$criteria)->queryScalar();

This is the most simple way to do that:

$count = Table::Model()
         ->count("field=:field", array("field" => $fildID));
echo $count;

That method is wrong! You trying to get by selecting all rows from database, you load the server, but that's wrong way! All you need to do :

$sql = "SELECT COUNT(*) FROM {{...table_name...}}";

$count = intval(Yii::app()->db
  ->createCommand($sql)
  ->queryScalar());

Or you can create function in your model:

Class User extends CActiveRecord
{
    private $_total;

    public function getTotalItems()
    {
        if( empty( $this->_total )) {
            $this->_total = intval(Yii::app()->db
                ->createCommand($sql)->queryScalar());
        }
        return $this->_total;
    }

}

then you can use this functions like this:

$totalItems = User::model()->totalItems;

or :

$model = User::model()->findByPk( $uid );
$totalItems = $model->totalItems;

or :

$model = new User;
$totalItems = $model->totalItems;

I strongly recommend you to find count with SQL query else it will degrade your system performance. There are three way to find out count with the SQL query itself in Yii 1 CActiveRecord , those are:

1. count() method

Finds the number of rows satisfying the specified query condition.

Example :

$count = Notification::model()->count('user_id'=> Yii::app()->user->uid);

2. countByAttributes() method (available since v1.1.4)

Finds the number of rows that have the specified attribute values.

Example :

$count = Notification::model()->countByAttributes(array(
    'user_id'=> Yii::app()->user->uid
));

3. countBySql() method

Finds the number of rows using the given SQL statement. This is equivalent to calling CDbCommand::queryScalar with the specified SQL statement and the parameters.

Example:

$count = Notification::model()
         ->countBySql("select *from notification where user_id=:userId",
            array(':userId'=>Yii::app()->user->uid)
           );

Don't use the following code, which will reduce system performance:

 $notifyModels = Notification::model()->findAllByAttributes(array( 'user_id'=> Yii::app()->user->uid )); $count = count($notifyModels); 

Because, there are two function call to find the count

在我的研究中,最简单和最佳实践如下。

$notifyModel = Notification::model()->count(array('user_id'=> Yii::app()->user->uid));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM