I have created Many To Many relationships on both levels (database and Models) for (User) and (Role) Models, now how can I assign many roles to the user id = 2 for instance: like below?
$user = User::find(2);
????
return view('index', compact(''));
By using attach and insert array for multiple roles
$roleId = [1, 2, 3];
$user->roles()->attach($roleId);
There's also sync method, the difference is sync remove all roles associated by user only if its not included in array of roleId
// User has role_id 1, 2, 3
$roleId = [1, 3];
$user->roles()->sync($roleId); // Role id 2 removed
Docs
Related
the problem is,
when I pluck the ids, a collection of ids returned
I need to get only the values
$transferOfficeId = $searchResults->pluck('office_id','office_id');
$vehicleId = $searchResults->pluck('vehicle_id','vehicle_id');
$agencyId = $searchResults->pluck('forAgency_id','forAgency_id');
$userId = $searchResults->pluck('addedBy_user_id','addedBy_user_id');
To get the names of these values by there ids
but here is not allowed because the ids are a collection not a values
$officeName = $bookingTransfersData->pluck('transferOffice.officeName','transferOffice.transfer_office_id')->get($transferOfficeId);
$vehicleName = $bookingTransfersData->pluck('vehicle.vehicleName','vehicle.vehicleName')->get($vehicleId);
$agencyName = $bookingTransfersData->pluck('agency.agencyName','agency.agencyName')->get($agencyId);
$userName = $bookingTransfersData->pluck('user.userName','user.userName')->get($userId);
return view('dashboard.index',compact('searchResults','fromDestinationName','toDestinationName','officeName', 'vehicleName','agencyName','userName'))
->with('i', (request()->input('page', 1) - 1) * 5);
I want to get the values of ids plucked,
to get columns by these ids from tables of each id like transferOfficeId,vehicleId .....
please help.
$projects = Project::find(collect(request()->get('projects'))->pluck('id')); // collect(...)->pluck('id') is [2, 1]
$projects->pluck('id'); // [1, 2]
I want the result to be in the original order. How do I achieve this?
Try $projects->order_by("updated_at")->pluck("id"); or "created_at" if that's the column you need them ordered by.
Referencing MySQL order by field in Eloquent and MySQL - SELECT ... WHERE id IN (..) - correct order You can pretty much get the result and have it order using the following:
$projects_ids = request()->get('projects'); //assuming this is an array
$projects = Project::orderByRaw("FIELD(id, ".implode(',', projects_ids).")")
->find(projects_ids)
->pluck('id'));
#Jonas raised my awareness to a potential sql injection vulnerability, so I suggest an alternative:
$projects_ids = request()->get('projects');
$items = collect($projects_ids);
$fields = $items->map(function ($ids){
return '?';
})->implode(',');
$projects = Project::orderbyRaw("FIELD (id, ".$fields.")", $items->prepend('id'))
->find($projects_ids);
The explanation to the above is this:
Create a comma separated placeholder '?', for the number of items in the array to serve as named binding (including the column 'id').
I solve this by querying the data one by one instead mass query.
$ids = collect(request()->get('projects'))->pluck('id');
foreach($ids as $id){
$projects[] = Project::find($id);
}
$projects = collect($projects);
$projects->pluck('id');
I have to do this manually because laravel collection maps all the element sorted by using ids.
Hi there can someone please help me I have this:
$users = User::where('user_group', (1 and 3))->where('deleted', 0)->get();
I want to take users that have user group 1 and 3 but its not working what I am doing wrong here ?!
Try:
$users = User::whereIn('user_group', [1,3])->where('deleted', 0)->get();
It sounds like what you are wanting is all users that have user_group 1 or 3, in which case it would be more like the following.
$users = User::whereIn('user_group', [1, 3])->where('deleted', 0)->get();
Found from the Laravel Query Builder page: https://laravel.com/docs/5.6/queries
If that isn't what you are looking for, can you please explain how your table is set up so that I can help further? Thanks!
Try this out. Not sure if you meant users that have BOTH user_groups 1 AND 3, or just users that have user_group 1 and users that have user_group 3.
use App\User;
$whereData = [
['user_group', 1],
['user_group', 3],
['deleted', 0]
];
$users = New User();
$users->where($whereData)->get();
I'm fighting with a problem for a considerable time, and I can't find a nice way to fix my issue.
Let's say I have two tables:
uses (id, name)
uses_phone (id, user_id, phone)
Supposing I have created a users (1, 'Mary') and her phones users_phones (1, 1, '123') (2, 1, '333')
If I want to update Mary, to change her name to "Maria":
The save() method will NOT delete the actual records in users_phone, but will insert new entries, and then I will have:
1, 1, 123
2, 1, 333
3, 1, 123
4, 1, 333
Which is the best way to solve this issue? I'm a bit confused. I like using Model instead PHQL (I like it too, but Models with ORM seems quie magic).
EDIT: Add code
I have updated my post to include the model relationships and a simplified version of my controller
Model Relationships:
class Users {
...
$this->hasMany('xid', 'UsersTelephones', 'xid_user', ['alias' => 'UsersTelephones']);
...
}
class UsersTelephones {
...
$this->belongsTo('xid_user', '\Users', 'xid', ['alias' => 'Users']);
...
}
(very simplified) Controller code:
function update($xid) {
...
$user = Users::findFirstByXid($xid);
// $user->email = "..";
$user_tfs = array();
for ($i=0;$i<count($tfs_array);$i++)
{
$user_tfs[$i] = new UsersTelephones();
$user_tfs[$i]->tf_number = $tfs_array[$i];
}
$user->UsersTelephones = $user_tfs;
// ...
$user->save()
}
Thanks for reading and please forgive my bad English.
Looking at your controller code, I have a few suggestions:
1) First, from where $tfs_array comes from?
2) You might also want to add the existing telephone record's id to the $user_tfs[$i] object, like: $user_tfs[$i]->id = $tfs_array[ID_OF_RECORD]; (you will need to add the record id to $tfs_array). This way, the ORM can interpret that the record already exists because the object has an id primary key.
3) Why do you want to iteratively add the UsersTelephones objects if all you want is to save the new name? You can go like:
$user = Users::findFirstByXid($xid);
$user->name = 'New Name';
$user->save();
4) You can also call the $model->update() method instead of save().
Here are more links:
https://docs.phalconphp.com/en/3.2/db-models#create-update-records
https://docs.phalconphp.com/en/3.2/db-models#create-update-with-confidence
https://docs.phalconphp.com/en/3.2/db-models-relationships#updating-related-records
I have 3 tables:
groups:
id, name
group_members:
id, group_id, user_id
users:
id
Now, what I'm looking to do, is to get all of the groups (just the groups), that have members associated with them
so, for instance i have the following:
groups
1, test
2, test-1
3, test-2
group_members
1, 1, 1
2, 1, 2
3, 3, 1
users
1
2
If I want to get all groups that user with id = 1 belongs to, it should return:
groups
1, test
3, test-2
Is there a way in eloquent that i can just return the groups (in a collection)
Thanks
You can use whereHas():
Group::whereHas('users', function($q) use($userId) {
$q->where('id', $userId);
})->get();
Or:
User::find($userId)->groups()->get();
Group::whereHas('members', function($q) use($userId) {
$q->where('user_id', $userId);
})->get();
This seems to work. I had to add some of the belongsTo etc relationships in my models