加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – Yii – 如何将模型数据检索到布局页面?

发布时间:2020-12-13 13:06:59 所属栏目:PHP教程 来源:网络整理
导读:我希望在我的布局main.php页面上列出一些类别名称. 由于布局没有任何关联的控制器或模型,我希望在Category模型上创建这样的静态方法: public static function getHeaderModels(){ // get all models here return $models;} 然后在主要布局中 ?php$models =
我希望在我的布局main.php页面上列出一些类别名称.
由于布局没有任何关联的控制器或模型,我希望在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,以便更有效地使用它.

首先创建一个新的小部件.假设名称为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') ?>

...

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读