如何在laravel中使用以下方法没有或其他优化的方法 [英] How to do the following with doesn't have or other optimized way in laravel

查看:73
本文介绍了如何在laravel中使用以下方法没有或其他优化的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个线程给出了答案,但是后来我发现我遇到了限制:

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?

因此创建一个新的线程,我确实有一个答案,但是现在我该如何使用诸如doesntHave之类的任何预构建函数或其他完全优化的函数来对其进行优化.

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?

推荐答案

我猜想用户和任务之间存在多对多的关系.为了使我的优化工作正常进行,我向User模型添加了以下关系,当我们过滤订阅的用户时将使用此关系.

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;

避免使用DB ::方法是一个经验法则,您应该能够在模型之间建立模型,而不必进行从一个模型到另一个模型的查询.

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.

这篇关于如何在laravel中使用以下方法没有或其他优化的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆