返回yii 2.0中指定AR类的静态模型

时间:2015-02-17 14:24:01

标签: php yii2

我想使用YII 2构建博客应用程序,我使用tbl_lookup表来存储整数值和其他数据对象所需的文本表示之间的映射。我按如下方式修改Lookup模型类,以便更轻松地访问表中的文本数据。在这里我的代码:

<?php
  namespace common\models;
  use Yii;
?>

class Lookup extends \yii\db\ActiveRecord
{
private static $_items=array();

public static function tableName()
{
    return '{{%lookup}}';
}   

public static function model($className=__CLASS__)
{
    return parent::model($className);
}

    /**
 * @inheritdoc
 */
public function rules()
{
    return [
        [['name', 'code', 'type', 'position'], 'required'],
        [['code', 'position'], 'integer'],
        [['name', 'type'], 'string', 'max' => 128]
    ];
}

/**
 * @inheritdoc
 */
public function attributeLabels()
{
    return [
        'id' => 'ID',
        'name' => 'Name',
        'code' => 'Code',
        'type' => 'Type',
        'position' => 'Position',
    ];
}

private static function loadItems($type)
{
    self::$_items[$type]=[];
    $models=self::model()->findAll([
        'condition'=>'type=:$type',
        'params'=>[':type'=>$type],
        'order'=>'position',
    ]);

    foreach ($models as $model)
        self::$_items[$type][$model->code]=$model->name;
}

public static function items($type)
{
    if(!isset(self::$_items[$type]))
        self::loadItems($type);
    return self::$_items[$type];
}

public static function item($type, $code)
{
    if(!isset(self::$_items[$type]))
        self::loadItems ($type);
    return isset(self::$_items[$type][$code]) ? self::$_items[$type][$code] : false;
}

}

但是当我想返回静态模型类

时,我遇到了一些错误
public static function model($className=__CLASS__)
{
    return parent::model($className);
}

有人帮我吗?哪里是我的错。 或者这里的任何人都有一些使用yii 2制作博客应用程序的教程? 谢谢。

1 个答案:

答案 0 :(得分:4)

在Yii2中,您不使用model()方法。因为,Yii2和Yii1是不同的(参见更多https://github.com/yiisoft/yii2/blob/master/docs/guide/intro-upgrade-from-v1.md)。在Yii1中提供类似的数据:

Post::model()->find($condition,$params);

在Yii2中提供类似的数据:

Post::find()->where(['type' => $id])->all(); 

查看更多https://github.com/yiisoft/yii2/blob/master/docs/guide/db-active-record.md

删除模型中的model

public static function model($className=__CLASS__)
{
    return parent::model($className);
}

loadItems方法更改为:

private static function loadItems($type)
{
    self::$_items[$type]=[];
    $models=self::findAll([
        'condition'=>'type=:$type',
        'params'=>[':type'=>$type],
        'order'=>'position',
    ]);

    foreach ($models as $model)
        self::$_items[$type][$model->code]=$model->name;
}