开启 Schema 缓存

Schema 缓存是一个特殊的缓存功能,每当你使用活动记录时应该要开启这个缓存功能。如你所知, 活动记录能智能检测数据库对象的集合(例如列名、列类型、约束)而不需要手动地描述它们。活动记录是通过执行额外的 SQL 查询来获得该信息。 通过启用 Schema 缓存,检索到的数据库对象的集合将被保存在缓存中并在将来的请求中重用。

在开发环境下,数据库表结构可能会经常变化,使用缓存可能会导致数据结构不一致的问题,所以主要用于生成环境。

要开启 Schema 缓存,需要配置一个 cache 应用组件来储存 Schema 信息,并在配置中设置
yii\db\Connection::enableSchemaCache 为 true:

需要注意的是,如果修改数据结构,在更新完 SQL 语句之后需要先关闭 Schema 再开启,数据结构的修改才会生效。

return [
    // ...
    'components' => [
        // ...
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=localhost;dbname=mydatabase',
            'username' => 'root',
            'password' => '',
            'enableSchemaCache' => true,

            // Duration of schema cache.
            'schemaCacheDuration' => 3600,

            // Name of the cache component used to store schema information
            'schemaCache' => 'cache',
        ],
    ],
];

转自 yii2优化 - 开启 Schema 缓存 - 简书 JustFantasy

文章目录