问题
I have a thread which gave the answer but later on I found that I was getting limitations: how to get list of users who are not under belongsToMany relation under a table in laravel?
so creating a new thread where I do have an answer but now how can I optimize the same with any prebuild functions like doesntHave
or something entirely else.
below is the code which gives me the list of users who are under a group and not assigned any task. one group can have multiple tasks so only users where the task is not assigned needs to be listed.
$gid = $task->group_id;
$MembersList = $task->members;
$group_subscribers = Group::with(['subscribedUsers' => function($q){
$q->select('id');
}])->whereId($gid)->get();
$group_subscribers = $group_subscribers[0]->subscribedUsers->pluck('id')->toArray();
$alreadyMembers = DB::table('task_user')->select('user_id as id')->whereIn('user_id', $group_subscribers)->pluck('id')->toArray();
$finalList = array_diff($group_subscribers, $alreadyMembers);
$users = User::whereIn('id', $finalList)->get();
return $users;
any way to improve the above code?
回答1:
I guessed Users and Tasks was in a many to many relationship. For my optimisation to work, i added the following relationship to the User model, this is gonna be used when we filter the subscribed users.
public class Users {
public function tasks() {
return $this->belongsToMany(Task::class);
}
}
Basically the implementation is filtering all the subscriber users and checking if they have tasks, since tasks is a relationship it returns a Collection and isNotEmpty()
is used for that reason.
$groupId = $task->group_id;
$group = Group::with(['subscribedUsers.tasks'])->find($groupId));
$withoutTasks = $group->subscribedUsers->filter(function ($user) {
return $user->tasks->isNotEmpty();
} );
return $withoutTasks;
It is a rule of thumb to avoid DB:: methods and you should be able to go to model to model, instead of making queries from getting from one model to another.
来源:https://stackoverflow.com/questions/59284155/how-to-do-the-following-with-doesnt-have-or-other-optimized-way-in-laravel