I am having a hard time finding a solution. If anyone could help me would be a great help. Let's say I have a user table like:
id | name | groupid |
---|---|---|
1 | john | 1 |
2 | brian | 2 |
3 | eddy | 1 |
4 | mia | 1 |
And when a new meeting is created(after fill up a form), I want to assign them a user like
id | groupid | user_id |
---|---|---|
1 | 1 | 1 |
2 | 1 | 3 |
3 | 1 | 4 |
4 | 1 | 1 |
5 | 1 | 3 |
6 | 1 | 4 |
7 | 1 | 1 |
8 | 1 | 3 |
How can I assign a user like this? Thanks in advance.
CodePudding user response:
Just create model classes for your entities for the User, Group, and then write your relationship function in your models. In your case, the relation type is Many To Many because you have many groups assigned to one user or vise-versa.
https://laravel.com/docs/9.x/eloquent-relationships#many-to-many-polymorphic-relations
And then use the attach on your user objects, group relation to assigning a user to group(s):
https://laravel.com/docs/9.x/eloquent-relationships#updating-many-to-many-relationships
$user = User::find(1);
$group = Group::find(1);
$user->group()->attach($group->id);
CodePudding user response:
You could count all the meetings by user and then select the one with the lowest count. However, this would be flawed if you added a new user. They would then be nominated for all meetings until they had caught up.
Keeping track in a round-robin fashion is harder. You can look at the most recent meeting, get the ID and then get all users (in the group), find the one last used, and then select the next in sequence.
You need to allow for wrapping so that if the last was 4, and there is no next user then it goes back to the first user.
Given an array of user ids as $id, and the most recently used as $current, returns $next for the ID of the user to use next
$next = $ids->search($current) 1;
if($next == $ids->count()) {
$next = 0;
}
$next = $ids[$next];