Search code examples
phplaravellaravel-5redispredis

laravel redis creating a set with ttl?


so for creating a set I can do

Redis::sadd('example',[1,4,6,1,])

I tried many variations to also create a set with a ttl non worked:

Redis::sadd('example',100,[1,4,6,1,])
Redis::sadd('example',[1,4,6,1,],100)
Redis::saddex('example',100,[1,4,6,1,])
Redis::saddex('example',[1,4,6,1,],100)

Solution

  • For additional reference, If you want to check whether a [sorted set] key (in your case, the 'example') exists or not, You can either do the ff:

    Proposal 1: (What you've preferred)

    $iTtlRedisKey = Redis::ttl('example');
    if ($iTtlRedisKey <= 0) {
        Redis::sadd('example', [1,4,6,1]);
        Redis::expire('example', 30);
    }
    
    $aSortedExampleSets = Redis::smembers('example');
    // array(3) { [0]=> string(1) "1" [1]=> string(1) "4" [2]=> string(1) "6" }
    

    Proposal 2: Using [exists] method

    $bCheckRedisKey = Redis::exists('example');
    if (boolval($bCheckRedisKey) !== true) {
        Redis::sadd('example', [1,4,6,1]);
        Redis::expire('example', 30);
    }
    
    $aSortedExampleSets = Redis::smembers('example');
    // same results as well.