通过Yii2 debug toolbar 发现有大量这种查询
SELECT
kcu.constraint_name,
kcu.column_name,
kcu.referenced_table_name,
kcu.referenced_column_name
FROM information_schema.referential_constraints AS rc
JOIN information_schema.key_column_usage AS kcu ON
(
kcu.constraint_catalog = rc.constraint_catalog OR
(kcu.constraint_catalog IS NULL AND rc.constraint_catalog IS NULL)
) AND
kcu.constraint_schema = rc.constraint_schema AND
kcu.constraint_name = rc.constraint_name
WHERE rc.constraint_schema = database() AND kcu.table_schema = database()
AND rc.table_name = 'my_user' AND kcu.table_name = 'my_user'
这个在查询数据库的 schema 信息,但是对于线上的产品,这样的查询是没有意义的,所以可以打开 Schema 缓存来避免多余的性能开销。
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=mydatabase',
'username' => 'root',
'password' => '',
'enableSchemaCache' => true, // 开启schema缓存
// Duration of schema cache.
'schemaCacheDuration' => 3600, // 缓存有效时间
// Name of the cache component used to store schema information
// 用来存储 schema 信息的缓存组件名称
'schemaCache' => 'cache',
],
提示
1、如果查询数据的时候使用了 asArray() 方法返回数组,是用不到 schema 缓存的。
2、如果修改了数据表的结构,比如增删字段,需要删除 schema 缓存才能生效,不然会报错。
// 方法一: 清空表结构缓存的方法
// 刷新 schema cache
Yii::$app->db->schema->refresh();
// 清楚指定表的 schema cache
Yii::$app->db->schema->refreshTableSchema($tableName);
// 方法二: 清空所有的缓存--不仅仅是 mysql 表结构
Yii::$app->cache->flush();
// 方法三: 使用 yii 命令行的方式 commond 清除缓存
cache/flush Flushes given cache components.
cache/flush-all Flushes all caches registered in the system.
cache/flush-schema Clears DB schema cache for a given connection component.
cache/index (default) Lists the caches that can be flushed.
// 执行
./yii cache/flush-all