Returns the static model of the specified AR class

2019-08-06 17:09发布

问题:

i want to build blog application using YII 2, i use the tbl_lookup table to store the mapping between integer values and textual representations that are needed by other data objects. i modify the Lookup model class as follows to more easily access the textual data in the table. here my code :

<?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;
}

}

but i get some error when i want to return the static model class

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

does anyone to help me ? where's my mistake. or anyone here have some tutorial to make blog application using yii 2 ? thank you.

回答1:

In Yii2 you don't use model() method. Because, Yii2 and Yii1 is different(see more https://github.com/yiisoft/yii2/blob/master/docs/guide/intro-upgrade-from-v1.md). In Yii1 to provide data like that:

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

In Yii2 to provide data like that:

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

See more https://github.com/yiisoft/yii2/blob/master/docs/guide/db-active-record.md

Delete model in your model:

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

And change loadItems method to:

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;
}


标签: php yii2