cache (chain operation 15)


cache can be used for select, find, value and column methods, as well as their derivative methods. After using the cache method, the database query operation will not be performed again within the cache validity period, but the cache will be obtained directly. For the data in the data cache, please refer to the cache section for the types and settings of data cache.

The following is an example. For example, we use the cache method for the find method as follows:

Db::table('user')->where('id',5)->cache(true)->find();

The first query result will be cached, and the second query for the same data will be returned directly. Contents in the cache without the need to query the database again.

By default, the cache validity period is determined by the default cache configuration parameters, but the cache method can be specified separately. For example:

Db::table('user')->cache(true,60)->find();
// 或者使用下面的方式 是等效的
Db::table('user')->cache(60)->find();

means that the cache validity period of the query results is 60 seconds.

The cache method can specify the cache identifier:

Db::table('user')->cache('key',60)->find();

Specifying the query cache identifier can make the query cache more efficient.

In this way, the query cache data can be directly obtained externally through the \think\Cache class, for example:

$result = Db::table('user')->cache('key',60)->find();
$data = \think\facade\Cache::get('key');

The cache method supports setting cache tags, for example:

Db::table('user')->cache('key',60,'tagName')->find();

Automatic cache update

The automatic cache update here means that the cache will be automatically cleaned once the data is updated or deleted (it will be automatically re-cached the next time it is obtained).

When you delete or update data, you can call the cache method of the same key, which will automatically update (clear) the cache. For example:

Db::table('user')->cache('user_data')->select([1,3,5]);
Db::table('user')->cache('user_data')->update(['id'=>1,'name'=>'thinkphp']);
Db::table('user')->cache('user_data')->select([1,3,5]);

The last queried data will not be affected by the first one. For the impact of query caching, ensure that the query and update or delete use the same cache identifier to automatically clear the cache.

If you use the primary key to query and update (or delete), the cache will be automatically updated without specifying the cache identifier

Db::table('user')->cache(true)->find(1);
Db::table('user')->cache(true)->where('id', 1)->update(['name'=>'thinkphp']);
Db::table('user')->cache(true)->find(1);