I’ve been using CodeIgniter for almost 6 months but now i’m changing to Yii framework. I’m figuring out the models and AR out for some time, i can’t seem to get used to it. In fact i think that i’m screwing up with the AR models.
Can someone please explain me the right way to extend the AR models with my own function that i can use in the controllers, it’s because I basically have many actions that repeat themselves and in the tutorials I only see a query being executed in a controller.
I can’t tell if this is the best way to do it, it may be.
This nearly minimal model is extended with a lookup method:
class Temp extends CActiveRecord
{
public static function model($className=__CLASS__) {
return parent::model($className);
}
public function tableName() {
return 'Temp';
}
public function rules() {
return array();
}
public function relations() {
return array();
}
public function attributeLabels() {
return array();
}
public function lookup($id=0) {
if($id != 0)
$ar = Temp::model()->findbyPk($id);
else
$ar = Temp::model()->findAll();
if (!isset($ar))
throw new CHttpException(500,'The requested items does not exist.');
return $ar;
}
}
Little addition: As long as you call your custom methods with Temp::model()…; You can also use $this in these methods:
public function findAllActiveUsers()
{
// Just an example. Could also be solved with a named scope.
return $this->findAllByAttributes(array('active'=>1));
}