我在 Laravel 模型中有一个函数,我需要检查我的密钥($key 变量)是否存在于 Redis 中,换句话说,我想创建一个条件,不允许来自 redis 的重复结果。这是我的功能。任何帮助表示赞赏。
功能
public static function cacheFields($fields)
{
foreach ($fields as $fieldname => $values) {
$key = static::$redisFieldKey.$fieldname; // here is that variable
Redis::pipeline(function ($pipe) use ($key, $values) {
foreach ($values as $value => $label) {
$pipe->hset($key, $value, $label);
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
当您hset对不存在的键执行时,它将set与字段及其对应的值进行散列。当您针对现有散列(和字段键)执行它时,它将update是现有散列字段的散列值。
127.0.0.1:6379> hset myhash myhashfield myvalue
(integer) 1
127.0.0.1:6379> hgetall myhash
1) "myhashfield"
2) "myvalue"
127.0.0.1:6379> hset myhash myhashfield anothervalue
(integer) 0
127.0.0.1:6379> hgetall myhash
1) "myhashfield"
2) "anothervalue"
127.0.0.1:6379>
Run Code Online (Sandbox Code Playgroud)
如果你想检查密钥是否存在,你可以使用existsO(1)
127.0.0.1:6379> exists myhash
(integer) 1
127.0.0.1:6379> exists nonexisting
(integer) 0
Run Code Online (Sandbox Code Playgroud)
如果要检查哈希字段是否存在,可以使用hexistsO(1)
127.0.0.1:6379> hexists myhash myhashfield
(integer) 1
127.0.0.1:6379> hexists myhash nonfield
(integer) 0
127.0.0.1:6379> hexists notmyhash myfield
(integer) 0
Run Code Online (Sandbox Code Playgroud)
编辑:
该文件指出,对于hset;
将存储在键中的散列中的字段设置为值。如果 key 不存在,则创建一个包含散列的新 key。如果字段已存在于哈希中,则将其覆盖。
| 归档时间: |
|
| 查看次数: |
4506 次 |
| 最近记录: |