Laravel updateOrCreate with hasMany relationship - php

I have users that can have multiple parameters. These are called for example user_param_1, user_param_2, ..., user_param_n. This is dynamic. It is a separate table user_parameters, which stores id, user_id, name and value. The relationship is a belongsTo and hasMany between Users and UserParameters. The problem is:
When editing, I want to keep it dynamically and if the user has an user_param_n+1, it should be created. But I already have problems to write the condition for the existing parameters.
I create myself an userParameters array, which contains from the $request variable only the necessary parameters. The array looks like this:
[
0 => [
"name" => "par1"
"value" => "var1"
]
1 => [
"name" => "par2"
"value" => "var2"
]
2 => [
"name" => "par3"
"value" => "var3"
]
]
Then I want to save it. My controller knows the user, so I can access to $user->id.
foreach ($userParameters as $userParameter) {
$user->parameters()->updateOrCreate(['id' => $user->parameters->id, 'user_id' => $user->id], $userParameter);
}
The issue is, that $user->parameters is an array of eloquent models. The condition is wrong. I can't access id directly. But how I can solve it? I need something like "['id' => [IF-DATABASE-ID-EXISTS-IN-ARRAY-$user-parameters]"... but how in an eloquent way?
Thanks in advance!
Best regards

I think you need to get the existing parameter using user_id and parameter_name cuz it's the uniqueness of that parameter row, if there is no parameter with this name it will create it with user_id & parameter_name and parameter_value passed to updateOrCreate function
foreach ($parameters_from_request as $parameter) {
$user->parameters()
->updateOrCreate(
[
'name' => $parameter['name'] ,
'user_id' => $user->id
],[
'name' => $parameter['name'],
'value'=> $parameter['value']
]);
}

Related

Saving many to many relations with a nested array in Laravel

So I have a many to many relation in Laravel. provider_locations has a ManyToMany relationship with transport_modes so I've made a pivot table, provider_locations_transport_modes
I have a form which generates a nested array like so:
0 => array [
"full_address" => "Full Address"
"phone_number" => "5555555"
"transport_modes" => array [
0 => "2"
1 => "1"
]
]
So on creation, I'm attempting something like
// First create Provider
$provider = Provider::create([
'name' => $data['providerName'],
'provider_code' => $data['providerCode'],
'phone_number' => $data['phoneNumber'],
]);
// Then create provider_location, associated with provider
foreach ($data['providerLocations'] as $providerLocation) {
$provider->ProviderLocations()->create([
'full_address' => $providerLocation['full_address'],
'phone_number' => $providerLocation['phone_number'],
]);
// Now attach values to pivot table?
foreach ($providerLocation['transport_modes'] as $transportMode) {
$provider->ProviderLocations()->TransportModes()->attach($transportMode);
}
}
It's been giving me the error that "Call to undefined method Illuminate\Database\Eloquent\Relations\HasMany::TransportModes()"
TransportMode.php has a belongsToMany relation with provider_locations, and ProviderLocation.php has a belongsToMany relation with transport_modes, so the relation should be set up correctly.
What am I doing wrong?

Adding a conditional value to extra column in pivot table from array in Laravel

I know the Question title is a bit murky, but here's what I'm trying to do:
I'm retrieving a list of groups that a user belongs to from a third party api. In some cases, the user will be an 'admin' for a group and other times, just a 'member'.
Specifics aside, I'm calling a method on my api class from my controller that hits the api, retrieves the user's groups, decides if they are an 'admin' or not, then returns an array of arrays with each group's information including a 'role' key that denotes whether or not they are an 'admin'. So my returned array looks something like this:
[
0 => [
'unique_id' => 1243657,
'name' => 'Group1',
'city' => 'Bluesville',
'state' => 'IN',
'role' => 'admin'
],
1 => [
'unique_id' => 4324567,
'name' => 'Group2',
'city' => 'New Curtsbourough',
'state' => 'WI',
'role' => 'member'
],
2=> [
'unique_id' => 87463652,
'name' => 'Group3',
'city' => 'Samsonite',
'state' => 'MN',
'role' => 'member'
]
]
Now, I need to take those groups and store them in the database, which I'm doing by checking first that the group doesn't exist in the database, then adding it if needed. Of course, I'm leaving off the role, as it is only relevant to the current user.
Next, I need to connect the current user to these groups that were just retrieved. I have a pivot table set up that currently holds the user_id and group_id.
The question is, how to best handle this. Before I decided that I needed to know whether or not a member was an 'admin' or not, I simply had my 'createGroups' method return an array of primary keys to me, then passed that array to a call to
$user->groups()->sync($array_of_ids);
However, with the added 'role' information, it's not as cut and dry.
Basically, at this point in the lifecycle, I have access to an array of groups that contains a field 'role'. My thinking says to add a 'role' field to the pivot table, which would then contain 'user_id', 'group_id' and 'role'. This means I'll not only need the $groups array with the retrieved groups, but the ids of those groups as they pertain to my database.
I could make something work, but I'm afraid it would be extremely messy and inefficient.
Thoughts anyone??
Ok, as happens many times on Stackoverflow, I've come to a solution for my own question. I'm posting so that in the off-chance someone stumbles upon my question needing to do something similar, they can at least see how one person handled it.
According to the Laravel docs, if you want to sync relationships with an added column, you need to call sync in the following way:
$user->groups()->sync([
1 => ['role' => 'admin'],
2 => ['role' => 'member'],
3 => ['role' => 'member']
]);
So before I could sync, I needed an array that resembled the array that is being passed to 'sync'.
Since I had an array of 'groups' that included a field called 'role' for each group, I created a 'createGroups' method that basically looped over the $groups array and called the 'insertGetId' method that Laravel provides. This method persists the object to the database and returns the primary key of the created record. For my 'createGroups' method, I did the following:
public function createGroups($groups)
{
$added = array();
foreach($groups as $group){
$id = $this->createGroup($group);
$added[$id] = ['role' => $group['role']];
}
return $added;
}
So as I'm inserting 'groups' into the database, I'm building up the array that is needed by the 'sync' method. Since the 'createGroup' method uses Laravel's 'insertGetId' method, it returns the primary key for that group. Then I use that id as the key to the array. After all groups are inserted, my 'added' array that is returned to my controller, looks like this:
[
1 => ['role' => 'admin'],
2 => ['role' => 'member'],
3 => ['role' => 'member']
]
which is exactly what the 'sync' method needs to do it's thing.
Happy coding!

MongoDB $lookup with _id as a foreignField in PHP

I am beating my head on the table for too long with this one...
I have two MongoDB collections: "chatroom" and "users". The "chatroom" collection has "user_id" key pointing to a specific single user in "users" collection.
I am trying to fetch the chatroom with a user using the $lookup aggregate query, what I currently have is this one:
$this->mongo->chatroom->aggregate(
array('$lookup' => array(
'from' => 'users',
'localField' => 'user_id',
'foreignField' => '_id',
'as' => 'user'
))
);
However, this returns an empty "user" field in the collection. The weird thing is that if I try to replace the "_id" with custom "uid" set to the value of _id.$id, it works as expected:
$this->mongo->chatroom->aggregate(
array('$lookup' => array(
'from' => 'users',
'localField' => 'user_id',
'foreignField' => 'uid', // uid = _id.$id
'as' => 'user'
))
);
I figured out the problem is that "_id" is ObjectId while "user_id" is a String. But I don't know how to deal with the problem nicely...
To answer my own question, I went around the problem by making "user_id" an instance of a "MongoId" class instead of a plain string. Basically, I store "user_id" as:
$mongoObject["user_id"] = new MongoId($this->user_id);
Another solution would probably be decorating the objects with "uid" field with a value equal to "_id.$id".

CakePHP 3 on view show the field from a belongTo association model

Lets say that i have the following associations schema:
Person => [
hasMany => [
Courses => [Person.id = Courses.person_id]
],
Courses => [
belongTo => [
Schools => [School.id = Courses.school_id]
]
When I view a person through mydomain/person/view/1 I need to have a table to show the Courses of that Person. Inside this table each Course need to show the name of the School.
So I tried the following on my controller:
public function view($id = null)
{
$person = $this->Persons->get($id, [
'contain' => [
'Courses.Schools',
]
]);
$this->set('persons', $test);
$this->set('_serialize', ['person']);
}
What I get on view is:
Person => [
firstname => test,
lastname => test,
courses => [
0 => [
id => 1,
shool_id => 1,
person_id => 1,
]
]
]
There is no school in the array although I used it in the contain option. So I can't display the name of the school. Am I doing anything wrong? Is there any guideline how can I show these fields on the view.
Basically I am sorry for this. This is a caused because of the debugKit. The debugkit is showing through the variables panel the associations only until the level I have mentioned but I used a var_dump and saw that the associations and the related fields are fetched/loaded correctly. I trusted the debugKit and I thought that they where not loaded.

Laravel: extra field sync with array

Im trying to save data inside a pivot table with an extra field called data.
when i save i have this array:
[
5 => "files"
4 => "pictures"
3 => "tags"
1 => "thumbs"
]
My table looks like this:
project_id
option_id
name
The ids shown above refer to option_id and the string to name inside the database.
When i try to use sync like this: $project->options()->sync($data);
$data is the array shown above
Im getting a error thats its trying to save the option_id with "files".
Here is how i build up the data that i use for sync:
Im trying to get what you suggested but dont know how to achieve it:
here is how i build up the array:
foreach($request->input('option_id') as $id) {
$option['option_id'][] = $id;
$option['data'][] = $request->input('data')[$id];
}
$data = array_combine($option['option_id'], $option['data']);
This is covered in the manual:
Adding Pivot Data When Syncing
You may also associate other pivot table values with the given IDs:
$user->roles()->sync(array(1 => array('expires' => true)));
In your example, you would have to change your array to look something like below but I believe this would translate to:
$data = [
5 => [ 'name' => "files" ],
4 => [ 'name' => "pictures" ],
3 => [ 'name' => "tags" ],
1 => [ 'name' => "thumbs" ],
];
$project->options()->sync($data);
I believe you may also need to modify how your Project model relates itself to your Options model:
// File: app/model/Project.php
public function options()
{
return $this->belongsToMany('Option')->withPivot('name');
}
This is also noted in the linked-to manual page:
By default, only the keys will be present on the pivot object. If your pivot table contains extra attributes, you must specify them when defining the relationship.
Update
Try creating your $data array like this:
$data = [];
foreach($request->input('option_id') as $id) {
$data[$id] = [ 'name' => $request->input('data')[$id] ];
}

Categories