【问题标题】:How can I update or delete a record from the JSON output using Laravel and Predis如何使用 Laravel 和 Predis 从 JSON 输出中更新或删除记录
【发布时间】:2016-09-10 11:53:37
【问题描述】:

几个月前我开始使用 Laravel,我想实现 Redis。

$test 更新或删除 1 条或多条记录的最佳方式和方法是什么。

    $allarticles = Article::all();
    $client = Redis::connection();
    $client->set('articles', $allarticles->toJson() );
    $test = $client->set('articles');

输出:

    [{
        "id":1,"title":"xQeMKGefAW","content":"44cuxAqVDS@gmail.com","created_at":null,"updated_at":null},{
        "id":2,"title":"a5wpRVRBNZ","content":"SsH9U5kF32@gmail.com","created_at":null,"updated_at":null},{
        "id":3,"title":"QF5xhsMh7d","content":"8erXnIojAM@gmail.com","created_at":null,"updated_at":null},{
        "id":4,"title":"gQVbDNbcmD","content":"27feouH6vc@gmail.com","created_at":null,"updated_at":null},{
        "id":5,"title":"FsOnoABBTg","content":"2qNutidwKZ@gmail.com","created_at":null,"updated_at":null},{
        "id":6,"title":"89sS4UASJl","content":"cQku7DBKSB@gmail.com","created_at":null,"updated_at":null},{
        "id":7,"title":"gpT3hO43V1","content":"EhzyEylbgw@gmail.com","created_at":null,"updated_at":null},{
        "id":8,"title":"1DKvbBn7yV","content":"0cSAxi9if3@gmail.com","created_at":null,"updated_at":null},{
        "id":9,"title":"pRr2LgzezC","content":"Aam0uuWLlF@gmail.com","created_at":null,"updated_at":null}

答案:

$allarticles = Article::all()->keyBy('id'); $client = Redis::connection();
$newarray = array(); 
foreach ( $allarticles->toArray() as $key => $value ){
    $newarray[$key] = json_encode($value); } $client->hmset('testtest', $newarray);
    $qwerty = $client->HGETALL('testtest'); 
    print_r($qwerty);
}

【问题讨论】:

    标签: json laravel redis predis


    【解决方案1】:

    不是将整个 json 存储为字符串,而是使用 hmset 命令将它们存储在 hashmap 中,id 是成员,json 的其余部分是值。

    http://redis.io/commands#hash

    设置json:

    hmset articles 1 {"title":"xQeMKGefAW","content":"44cuxAqVDS@gmail.com","created_at":null,"updated_at":null} 2 {"title":"xQeMKGefAW","content":"44cuxAqVDS@gmail.com","created_at":null,"updated_at":null} and so on
    

    要检索整个 json:

    hgetall articles
    

    要更新一个或多个值,请使用 HMSET

    要删除一个或多个值,请使用 HDEL

    希望这会有所帮助。

    【讨论】:

    • 我该怎么做,我必须做一个循环吗?
    • 你需要从你的 Json 中获取一个键值对,例如一个 hashmap。这取决于您的应用程序逻辑,然后一次调用 Hmset 即可完成这项工作。同样 hgetall 和heel 是单调用。
    • 希望你能给我举个例子:)
    • 我做了以下: $allarticles = Article::all()->keyBy('id'); $client = Redis::connection(); $newarray = 数组(); foreach ( $allarticles->toArray() as $key => $value ){ $newarray[$key] = json_encode($value); } $client->hmset('testtest', $newarray); $qwerty = $client->HGETALL('testtest'); print_r($qwerty);这是正确的方法吗?
    猜你喜欢
    • 2019-06-19
    • 1970-01-01
    • 1970-01-01
    • 2019-05-26
    • 2019-11-01
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多