How should I use redis? - laravel

I'm doing an api in laravel and I want to use Redis. I'm not sure if I'm doing well.
How should I use Redis to store json and then get a value by ID or another column.
Should I save the json as plain text? Then how do I go through it to look for a specific value or how you should keep the values?
{
"id": 1,
"name": "Package A",
"dimensions": "100x100x100",
"created_at": "2019-05-29 01:35:53",
"updated_at": "2019-05-29 01:35:53"
},
{
"id": 2,
"name": "Package B",
"dimensions": "150x150x150",
"created_at": "2019-05-29 01:36:53",
"updated_at": "2019-05-29 01:36:53"
}
$package = Package::where->get();
Redis::hmset('packages', array($package));
Or I shoud ..
$package = Package::where->get();
Redis::set('packages', serialize($package));
Then How I get a value?
For example: all fields id=2

I recommend saving the information in the following way, so it is easier to access later.
Package::all()->each(function($package){
Redis::set("package:{$package->id}", $package->toJson());
});
And if you need to recover information :
json_decode(Redis::get("package:$id"), true);
In redis you have to consider how to access the information, and then how to save it. For example, if you want to search by name, your key will be composed of the same name.
If you want retrive all packages from Redis, you will need all of packages key´s.
The folowing command retrive all keys matches with the structure :
Redis::keys('package:*');
After that, you can do the following
$keys = Redis::keys('package:*');
$packages = [];
foreach ($keys as $key){
array_push($packages, json_decode(Redis::get($key), true));
}
return $packages;

Related

Streamsets Data Collector: Replace a Field With Its Child Value

I have a data structure like this
{
"id": 926267,
"updated_sequence": 2304899,
"published_at": {
"unix": 1589574240,
"text": "2020-05-15 21:24:00 +0100",
"iso_8601": "2020-05-15T20:24:00Z"
},
"updated_at": {
"unix": 1589574438,
"text": "2020-05-15 21:27:18 +0100",
"iso_8601": "2020-05-15T20:27:18Z"
},
}
I want to replace the updated_at field with its unix field value using Streamsets Data Collector. As far as I know, it can be done using field replacer. But I'm still didn't get it how to make a mapping expression. How can I achieve that?
In Field Replacer, set Fields to /rec/updated_at and New value to ${record:value('/rec/updated_at/unix')} and it will replace the value. See below.
Cheers,
Dash

How to fetch data using with via object in Laravel eloquent?

Actually, I want to fetch data using Model object not through Model facade like mention below.
$user = $this->getGuard()->user();
Above user is current logged user which is
"id": 6,
"name": "kuser",
"email": "kuser#gmail.com",
"phone": "03345154067",
"is_subscribed": 0,
"subscription_date": null
But when I try to fetch same $user object with its related model like cards, by execute $user->with(['cards'])->first(); than it gives first record of user table with cards like mentioned below.
"id": 1,
"name": "admin",
"email": "admin#gmail.com",
"phone": "03056494616",
"is_subscribed": 1,
"subscription_date": "2019-10-08",
"cards": []
Above mentioned record which is user object. It is first record of my user table.
Actually, I am expecting.
"id": 6,
"name": "kuser",
"email": "kuser#gmail.com",
"phone": "03345154067",
"is_subscribed": 0,
"subscription_date": null
with its related model cards like
"id": 6,
"name": "kuser",
"email": "kuser#gmail.com",
"phone": "03345154067",
"is_subscribed": 0,
"subscription_date": null
"cards":[] // array of cards those belongs to it.
You can use Lazy Eager Loading, you don't have to query for the user again, you already have it:
$user = $this->getGuard()->user();
$user->load('cards');
Laravel 6 Docs - Eloquent - Relationships - Lazy Eager Loading
Use a simple where ?
$user->where('id', Auth::id())->with(['cards'])->first();
won't that work?
Here is another way
User::with(['cards'])->find($user->id);

Array with single attribute of many-to-many Eloquent relationship

I created a model NearMiss that has a many-to-many relationship with a Type model. When there is a GET request for a specific NearMiss, I want an array to be attached to the JSON output that has the name attribute of all Type instances that belong to the NearMiss instance.
I can attach an array of Types to the output, but I want to get rid of all the additional information (such as pivot information).
The GET request /nearmisses/{nearmiss} executes the following method:
public function show($id)
{
try {
$nearmiss = NearMiss::findOrFail($id)->first();
$nearmiss->types->makeHidden(['id', 'created_at', 'updated_at']);
return response()->json($nearmiss);
} catch(ModelNotFoundException $e) {
abort(400, 'Model not found');
}
}
The NearMiss model has the following types relation:
public function types()
{
return $this->belongsToMany('App\Type', 'near_miss_type', 'near_miss_id', 'type_id');
}
Current output:
{
"id": 1,
"location_long": "0.0000000",
"location_lat": "0.0000000",
"employee_id": 1,
"created_at": "2019-02-11 16:38:24",
"updated_at": "2019-02-11 16:38:24",
"types": [
{
"id": 1,
"name": "Brandgevaar"
"created_at": "2019-02-11 16:33:25",
"updated_at": "2019-02-11 16:33:25",
},
{
"id": 2,
"name": "Slipgevaar",
"created_at": "2019-02-11 16:34:12",
"updated_at": "2019-02-11 16:34:12",
}
]
}
I know that I can remove additional attributes (such as id, created_at, updated_at), but that still leaves me with an array of Type instances (with just a single name attribute). When I try flatten() I receive an error that flatten() can't be used on BelongsToMany relationships.
Desired output:
{
"id": 1,
"location_long": "0.0000000",
"location_lat": "0.0000000",
"employee_id": 1,
"created_at": "2019-02-11 16:38:24",
"updated_at": "2019-02-11 16:38:24",
"types": [
"Brandgevaar", "Slipgevaar"
]
}
Can someone help me to get the desired output please.
You could load the types manually and use the pluck() function to only get the name of each type.
$nearmiss->types = $nearmiss->types()->pluck('name');
However I'm not sure if this will interfere with the magic properties from Eloquent.

Laravel Api resource controller json format

I managed to change the format for the json response of the laravel resource controller for APIs, i want to make a key -> value response but i cant find the way to remove the brackets:
the response i get is this:
{
"1": [
{
"updated_at": 1536147154
}
],
"2": [
{
"updated_at": 1536160598
}
]
}
but i want it to be like this:
{
"1":
{
"updated_at": 1536147154
},
"2":
{
"updated_at": 1536160598
}
}
I get the response from an eloquent collection, and then I group it by id, but I don't know how to get rid of the brackets because the values end in an array.
I don't know if I am clear in my question.
Solved it, i removed the groupby and instead, I used the keyBy to assign their id as a key.
Transformers can be used to format json
I used https://github.com/spatie/laravel-fractal to format my json response in controllers

Find matching array items in MongoDB document

I am developing a web app using Codeigniter and MongoDB.
In the database I got a document that look like this:
{
"_id": {
"$id": "4f609932615a935c18r000000"
},
"basic": {
"name": "The project"
},
"members": [
{
"user_name": "john",
"role": "user",
"created_at": {
"sec": 1331730738,
"usec": 810000
}
},
{
"user_name": "markus",
"role": "user",
"created_at": {
"sec": 1331730738,
"usec": 810000
}
}
]
}
I need to search this document using both user_name and role. Right now when I am using the below code I get both. I only want to get array items matching both user_name and role.
$where = array (
'_id' => new MongoId ($account_id),
'members.user_id' => new MongoId ($user_id),
'members.role' => $role
);
$this -> cimongo -> where ($where) -> count_all_results ('accounts');
This is an old question, but as of MongoDB 2.2 or so you can use the $ positional operator in a projection so that only the matched array element is included in the result.
So you can do something like this:
$this->cimongo->where($where)->select(array('members.$'))->get('accounts');
This is a repeat of this question:
Get particular element from mongoDB array
Also you might want to use $elemMatch
http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-ValueinanArray
Here is the rub -- you aren't going to be able to get the array items that match because mongo is going to return the entire document if those elements match. You will have to parse out the code client side. Mongo doesn't have a way to answer, "return only the array that matches."

Resources