Sunday, June 30, 2013

Yii Active Records

Yii Active Record

PostController.php

//Assuming we have a database table with ID, title, content, category_id and user_id as a field

public function actionActiveRecord()
{
  //example of what Yii Active record can return
  $model = Post::model()->find('id = 1');
  echo $model->title;
  $model = Post::model()->find('category_id = 2 AND user_id = 1');
  echo $model->title;

  //alternatively you can use Yii Active record find by attributes
  $model = Post::model()->findByAttributes(array(
      'category_id' => 2,
      'user_id'     => 1,
  ));
 
  echo $model->title;

  //or you can use findByPk
  $model = Post::model()->findByPk(1)

  //if you need to display more than 1 data findAll
  $model = Post::model()->findAll('category_id = 2');
  foreach($model as $m){
    echo $m->title."<br/>";
    echo $m->content."<br/>";
  }
}

No comments:

Post a Comment