......... mbatik lagi dengan php......
I want to create an inherited model (class) from another model, as illustrated in Yii's wiki entry: Single Table Inheritance.
The tutorial uses defaultScope()
in differentiating the Car
model into SportCar
, FamilyCar
by applying conditions or filters on the Car
's attribute 'type
'. This, however, doesn't work when one wants to create new SportCar
—the child— object. I would have to call setAttribute('type','sport')
whenever the SportCar
model is to be passed into create forms. defaultScope()
is only useful for search/find operation (used as default parameter in a CDbCriteria
instance, for example), as stated in Yii Class Reference:
[...] Note, default scope only applies toSELECT
queries. It is ignored forINSERT
,UPDATE
andDELETE
queries.
The workaround I use is to override the init()
method in the inherited model/class. The CActiveRecord
Class Reference says:
[...] This method is invoked when an AR instance is newly created and has its scenario set. You may override this method to provide code that is needed to initialize the model (e.g. setting initial property values.).
class SportCar extends Car { //... /** * override the init() function to initialize variables */ function init(){ parent::init(); // initialize the 'type' attribute $this->__set('type','Sport'); } ... }
This works fine so far. Using CActiveForm
, the SportCar
and FamilyCar
models would return the intended types —'sport' or 'family'— in create/update form fields.
No comments
Post a Comment