function in model

Hi all,

I want to list a data based on user search.

code UserController as below :

	public function actionList()


		$userx = $_GET[user];


			$pages=new CPagination(user::model()->searchByUserId($userx)->count());






			$criteria = new CDbCriteria;

			$pages=new CPagination(user::model()->count($criteria));











code user model as below


public function searchByUserID(&#036;userx){

    &#036;criteria = new CDbCriteria;

    &#036;criteria-&gt;condition = &quot;user_name LIKE :username&quot;;


    &#036;cari =  user::model()-&gt;findAll(&#036;criteria);

	return &#036;cari;



how to add function in model, ex: searchByUserId to return data base on $userx parameter ?

if able, how to count the row from that function return?

please advice. thanks.

the error for codes above is :

Fatal error: Call to a member function count() on a non-object in C:\xampp\htdocs\tugas\protected\controllers\UserController.php on line 127

anyone can help me please …?

maybe if you extend CActiveRecord

but, why not use existing methods of the class?.



well, how to add more search criteria in model as function ?

could you give me example code ?

This is my function, but its not works.

public function searchByUserID($userx){

$criteria = new CDbCriteria;

$criteria->condition = "user_name LIKE :username";


$cari = user::model()->findAll($criteria);

return $cari;

after I got that function, hoe to return the count or the rows returned ?

I used this code, but its not works too.

print_r user::model()->searchByUserID($userx)->count();

Please help.

Ok, I have checked, that my function is correct. My problem now, how to return the count of that function row ?

The returned result ($cari) can be treated as an array, so use foreach to process the result, count the number of array elements (php function), etcetera.

I think you need to use scopes

public function scopes(){

    return array(

              'fromUser' => array('condition'=> "user_name LIKE :username")



public function fromUser($username){

    $this->getDbCriteria()->mergeWith(array('params' => array('username'=>$username)));

    return $this;


After that, you can use




Thank you Ricardo, I have try, but the result of count is always same to count all records.

I have 4 record, when I call user::model()->fromUser(‘whatevername’)->count() it will return 4.

Is there any wrong with the code ?


My fault…You don’t need scope definition, just the function:

public function fromUser($username){



            'condition'=> "username = :user_name", 

            'params' => array('username'=>$username)));


        return $this;