Powered by Blogger.

Understanding Yii Active Record API

how to fetch and write data with Active Record

small tip

In these functions if having "All" part it returns an array of objects and then you should use foreach loop

foreach($objects as $object){

    echo $object->attribute ;

}

Functions don't have "All" part it returns an object and you can access as

$object->attribute

find

$model=Products::model()->find('category_id=:category_id',array(':category_id'=>4));

This returns one object so you can access results as

    echo $model->name;

findAll

$model=Products::model()->findAll('category_id=:category_id',array(':category_id'=>4));

This returns one an array of objects so you can access results as

    foreach($model as $product){

        echo $product->name;

    }

findByPk

$model=Products::model()->findByPk(1,array('condition'=>'category_id=:category_id','params'=>array(':category_id'=>1)));

This returns one object so you can access results as

    echo $model->name;

findAllByPks

$model=Products::model()->findAllByPk(array(2,3,10),array('condition'=>'category_id=:category_id','params'=>array(':category_id'=>0)));

This returns one an array of objects so you can access results as

    foreach($model as $product){

        echo $product->name;

    }
findByAttributes

$model=Products::model()->findByAttributes(array('id'=>1);

This returns an Product object so you can access results as

    echo $model->name;

findAllByAttributes

$model=Products::model()->findAllByAttributes(array('id'=>array(1,2,3,4));

This returns an array of product objects so you can access results as

    foreach($model as $product){

        echo $product->name;

    }


findBySql

$model=Products::model()->findBySql("select * from product where id=:id",array('id'=>10));

This returns an Product object so you can access results as

    echo $model->name;

findAllBySql

$model=Products::model()->findAllBySql("select * from product where category_id=:category_id",array('category_id'=>5));

This returns an array of product objects so you can access results as

    foreach($model as $product){

        echo $product->name;

    }

that's it !
Categories: