Reputation: 2400
I started a few months ago with Laravel and I want to implement Redis.
How and what is the best way to update or delete 1 or more records from $test
.
$allarticles = Article::all();
$client = Redis::connection();
$client->set('articles', $allarticles->toJson() );
$test = $client->set('articles');
Output:
[{
"id":1,"title":"xQeMKGefAW","content":"[email protected]","created_at":null,"updated_at":null},{
"id":2,"title":"a5wpRVRBNZ","content":"[email protected]","created_at":null,"updated_at":null},{
"id":3,"title":"QF5xhsMh7d","content":"[email protected]","created_at":null,"updated_at":null},{
"id":4,"title":"gQVbDNbcmD","content":"[email protected]","created_at":null,"updated_at":null},{
"id":5,"title":"FsOnoABBTg","content":"[email protected]","created_at":null,"updated_at":null},{
"id":6,"title":"89sS4UASJl","content":"[email protected]","created_at":null,"updated_at":null},{
"id":7,"title":"gpT3hO43V1","content":"[email protected]","created_at":null,"updated_at":null},{
"id":8,"title":"1DKvbBn7yV","content":"[email protected]","created_at":null,"updated_at":null},{
"id":9,"title":"pRr2LgzezC","content":"[email protected]","created_at":null,"updated_at":null}
Answer:
$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);
}
Upvotes: 0
Views: 335
Reputation: 5679
Instead of storing the whole json as a string, store them in a hashmap using hmset command, id is the member and rest of the json is the value.
To set the json:
hmset articles 1 {"title":"xQeMKGefAW","content":"[email protected]","created_at":null,"updated_at":null} 2 {"title":"xQeMKGefAW","content":"[email protected]","created_at":null,"updated_at":null} and so on
To retrieve the whole json:
hgetall articles
To update one or more values use HMSET
To delete one or more values use HDEL
Hope this helps.
Upvotes: 1