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

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);

Related

How to create a Follower following model in GraphQL?

I saw many tutorials/article they have mentioned that following/followers field as an integer in user model in GraphQL schema. I know those are for demo purpose. But I don't know how to save the followers/following users with proper relational model and how unfollow works. I saw Twitter developer site here they mentioned their user model as follows:
{
"id": 6253282,
"id_str": "6253282",
"name": "Twitter API",
"screen_name": "TwitterAPI",
"location": "San Francisco, CA",
"profile_location": null,
"followers_count": 6133636,
"friends_count": 12,
"listed_count": 12936,
"created_at": "Wed May 23 06:01:13 +0000 2007",
"favourites_count": 31,
}
I don't know whether this is their original code or prototype. But I'm confused how they are saving the follower userID.
1. How can we create proper follower/following model in graphQL?
2. Also how to create post likes/dislikes in GraphQL?

Is there an API that shows the user task histroy on the Camunda side?

I have a Camunda flow, there are 2-3 user tasks in this flow. I want to see their history after completing these tasks. There are a couple of methods, but I just want to get both the label and the entered value with rest-api.
I can't get them directly with rest-api.
The following method returns variables with the processInstanceId.
List<HistoricVariableInstance> instances = historyService.createHistoricVariableInstanceQuery()
.processInstanceId(processIntanceId)
.list();
but I need to call another rest-api to get the labels. GET /process-definition/{id}/xml with this api.
Other topics have been opened for this, but it does not meet exactly what I want.
similar question
I think you are right, you need 2 steps. I would combine the following requests:
First get all User Tasks:
GET /history/task -see API Reference
From its result Array you need the id and the name (which is the label):
[{"id":"anId",
...
"name":"aName",
...
}]
Now you can get the variables for each UserTask, like
GET /history/variable-instance?taskIdIn=YourTaskId see API Reference
https://docs.camunda.org/manual/7.16/reference/rest/history/variable-instance/post-variable-instance-query/
returns the name (label) and the value of the process variables
[
{
"id": "someId",
"name": "someVariable",
"type": "Integer",
"variableType": "integer",
"value": 5,
"valueInfo": {},
"processDefinitionKey": "aProcessDefinitionKey",
"processDefinitionId": "aProcessDefinitionId",
"processInstanceId": "aProcInstId",
"executionId": "aExecutionId",
"activityInstanceId": "aActivityInstId",
"caseDefinitionKey": null,
"caseDefinitionId": null,
"caseInstanceId": null,
"caseExecutionId": null,
"taskId": null,
"tenantId": null,
"errorMessage": null,
"state": "CREATED",
"createTime":"2017-02-10T14:33:19.000+0200",
"removalTime": "2018-02-10T14:33:19.000+0200",
"rootProcessInstanceId": "aRootProcessInstanceId"
}
]

How should I use redis?

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;

Return a Boolean instead of the whole collection

The Stack model can have "user progress", users can "clear" stacks. And that progress is stored in the Progress model.
Progress model:
public function stack(){
return $this->belongsTo(Stack::class);
}
It would be neat if it was possible to fetch all stacks, and if the user has "cleared" it or not, with a boolean true or false. I don't won't to fetch all data corresponding to the progress. So I have tried setting up a "finished" relation on the Stack model
public function finished(){
return $this->hasOne(Progress::class) ? true : false;
}
But this setup gives me the following error
Call to a member function addEagerConstraints() on boolean.
This is how I call the relationship at the moment
$user = \App\Stack::with(['finished' => function($q){
return $q->where('user_id', auth()->user()->id);
}])->get();
But that returns the whole collection, and that is not necessary. The expected result should be like:
{
"id": 5,
"user_id": 2,
"subject_id": 2,
"name": "tstar igen",
"slug": "tstar-igen",
"description": "asdasd",
"image": null,
"created_at": "2017-10-06 08:27:36",
"updated_at": "2017-10-06 08:27:36",
"finished": true/false
},
So lets say that here is an relation entry in in the progress table for the stack above.
+----+---------+----------+
| id | user_id | stack_id |
+----+---------+----------+
| 1 | 1 | 5 |
+----+---------+----------+
So when fetching the stacks, with relation finish. The finished column should be true or false. So the return from Stack, with relation finished should be like the following. Notice the finished column changed to false on the last stack, because the relation is not present in the progress table.
{
"id": 5,
"user_id": 2,
"subject_id": 2,
"name": "tstar igen",
"slug": "tstar-igen",
"description": "asdasd",
"image": null,
"created_at": "2017-10-06 08:27:36",
"updated_at": "2017-10-06 08:27:36",
"finished": true
},
{
"id": 6,
"user_id": 2,
"subject_id": 2,
"name": "another stack",
"slug": "another-stack",
"description": "This is a test stack for all the stacks out there",
"image": null,
"created_at": "2017-10-06 08:27:36",
"updated_at": "2017-10-06 08:27:36",
"finished": false
},
You can try withCount that counts your related models. But it will return number of related models not boolean. Here is an example:
Stack.php
public function progress(){
return $this->hasOne(Progress::class);
}
then:
\App\Stack::withCount('progress')->get();
Now results have count_progress attribute with number of related 'Progress' models. Because your relation is hasOne it should be 0 or 1.
You are almost done, You have your relationship setup well except for the boolean stuffs, remove it:
public function finished(){
return $this->hasOne(Progress::class);
}
Then when you need to check you can use has or whereHas relationship method:
$stack = \App\Stack::whereHas('finished', function($q){
return $q->where('user_id', auth()->user()->id);
})->get();
Based on your need thats the best I could conceive. I think this should be sufficient.
It would do well to learn how has and whereHas works. But just to summarize: has simply is like whereHas except that it checks if there is at least one model related to the first model, and the other helps you to make more advanced constraints as shown in the example I gave.
Your model
public function progress(){
return $this->hasOne(Progress::class);
}
Your controller
...
$stacks->load('progress');
resource
'finished' => $this->whenLoaded('progress')->isNotEmpty()

RestKit 2.0 - Mapping json array to an enity relationship loses array sequence

I have a problem mapping json to CoreData and reading it out again. I map from json to an Activity-Entity with a relationship of last participant entities. The last_particpants is an array with the most recent participants, ordered from most recent first by the API.
{
"id": 50,
"type": "Initiative",
"last_participants": [
{
"id": 15,
"first_name": "Chris",
},
{
"id": 3,
"first_name": "Mary",
},
{
"id": 213,
"first_name": "Dany",
}
]
}
I have RestKit logging on and see that the mapping reads the array elements one by one and keeps the order. However CoreData saves them as an NSSet of entities and then the order gets lost. When I read out the data its is mixed up. What options do I have to keep the order in which the array was mapped? Any help would be great.
2 options:
Use an ordered set in Core Data (set on the attribute in the properties inspector).
Use the #metadata provided by RestKit to access the collection order during mapping.

Resources