我想使用YI2构建博客应用程序,我使用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);
}
有人帮我吗?我的错在哪里。或者这里有人有一些使用yii2制作博客应用程序的教程吗?非常感谢。
在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;
}