我希望在我的布局main.PHP页面上列出一些类别名称.
由于布局没有任何关联的控制器或模型,我希望在Category模型上创建这样的静态方法:
由于布局没有任何关联的控制器或模型,我希望在Category模型上创建这样的静态方法:
public static function getHeaderModels() { // get all models here return $models; }
然后在主要布局中
<?PHP $models = Category::getHeaderModels(); foreach($models as $model) { // .... } ?>
我的问题是一个非常基本的问题:
如何从模型中检索这些类别名称?
这是完整的模型:
class Category extends CActiveRecord { public static function model($className=__CLASS__) { return parent::model($className); } public function tableName() { return 'category'; } public function rules() { return array( array('parent_id','numerical','integerOnly' => true),array('name','length','max' => 255),array('id,parent_id,name','safe','on' => 'search'),); } public function relations() { return array( 'users' => array(self::MANY_MANY,'User','categories(category_id,user_id)'),); } public function scopes() { return array( 'toplevel'=>array( 'condition' => 'parent_id IS NULL' ),); } public function attributeLabels() { $id = Yii::t('trans','ID'); $parentId = Yii::t('trans','Parent'); $name = Yii::t('trans','Name'); return array( 'id' => $id,'parent_id' => $parentId,'name' => $name,); } public function search() { $criteria = new CDbCriteria; $criteria->compare('id',$this->id); $criteria->compare('parent_id',$this->parent_id); $criteria->compare('name',$this->name,true); return new CActiveDataProvider(get_class($this),array( 'criteria' => $criteria,)); } public static function getHeaderModels() { //what sintax should I use to retrieve the models here ? return $models; }
可能这个答案可以帮到你.首先,您必须创建一个Widget,以便更有效地使用它.
原文链接:https://www.f2er.com/php/136361.html首先创建一个新的小部件.假设名称为CategoryWidget.将此小部件放在组件目录protected / components下.
class CategoryWidget extends CWidget { public function run() { $models = Category::model()->findAll(); $this->render('category',array( 'models'=>$models )); } }
然后为此窗口小部件创建一个视图.文件名是category.PHP.
把它放在protected / components / views下
category.PHP
<?PHP if($models != null): ?> <ul> <?PHP foreach($models as $model): ?> <li><?PHP echo $model->name; ?></li> <?PHP endforeach; ?> </ul> <?PHP endif; ?>
然后从主布局中调用此小部件.
main.PHP
// your code ... <?PHP $this->widget('CategoryWidget') ?> ...