Schema缓存是一个比较特殊的缓存,只有当我们使用活动记录是这个缓存才会生效。
什么是活动记录文章源自懂站帝-http://www.sfdkj.com/18248.html
活动记录能智能检测数据库对象的集合(例如列名、列类型、约束)而不需要手动地描述它们。活动记录是通过执行额外的SQL查询来获得该信息。 通过启用 Schema 缓存,检索到的数据库对象的集合将被保存在缓存中并在将来的请求中重用。文章源自懂站帝-http://www.sfdkj.com/18248.html
Schema缓存开启的方法:文章源自懂站帝-http://www.sfdkj.com/18248.html
要开启Schema缓存,需要配置一个cache应用组件来储存Schema信息,并在配置中设置 yii\db\Connection::enableSchemaCache 为true:文章源自懂站帝-http://www.sfdkj.com/18248.html
return [文章源自懂站帝-http://www.sfdkj.com/18248.html
// ...文章源自懂站帝-http://www.sfdkj.com/18248.html
'components' => [文章源自懂站帝-http://www.sfdkj.com/18248.html
// ...文章源自懂站帝-http://www.sfdkj.com/18248.html
'cache' => [文章源自懂站帝-http://www.sfdkj.com/18248.html
'class' => 'yii\caching\MemCache', //配置缓存组件,这里用了memcache文章源自懂站帝-http://www.sfdkj.com/18248.html
],文章源自懂站帝-http://www.sfdkj.com/18248.html
'db' => [文章源自懂站帝-http://www.sfdkj.com/18248.html
'class' => 'yii\db\Connection',文章源自懂站帝-http://www.sfdkj.com/18248.html
'dsn' => 'mysql:host=localhost;dbname=mydatabase',文章源自懂站帝-http://www.sfdkj.com/18248.html
'username' => 'root',文章源自懂站帝-http://www.sfdkj.com/18248.html
'password' => '',文章源自懂站帝-http://www.sfdkj.com/18248.html
'enableSchemaCache' => true, //开启schema缓存文章源自懂站帝-http://www.sfdkj.com/18248.html
// Duration of schema cache.文章源自懂站帝-http://www.sfdkj.com/18248.html
'schemaCacheDuration' => 3600, //有效时间文章源自懂站帝-http://www.sfdkj.com/18248.html
// Name of the cache component used to store schema information文章源自懂站帝-http://www.sfdkj.com/18248.html
'schemaCache' => 'cache',
],
],
];
需要注意的是
1、若是修改了数据表的结构,或者添加,删除了字段,都需要将enableSchemaCache设置为false之后才能生效。
2、查询语句时若是使用了asArray(),schema缓存是无效的。