drny20290570 2019-02-27 09:07
浏览 91

如何获取通过特定策略的所有用户的列表?

When a project is added, I fetch all users who have the permission to view it to inform them.
This happens in a listener:

use App\Models\User;
use Illuminate\Support\Facades\Gate;

// ...

$notifiables = User::all()->filter(function(User $user) use($event) {
    return Gate::forUser($user)->allows('view', $event->project);
});

This works. But when I've got 1000 users in my system and 5 are able to view the project, I'm iterating over 995 users for nothing.
And as the event and the listener run synchronously, the user adding a project has to wait for this to happen.

How can I accelerate this?

Edit: Okay, it's possible to queue listeners. However, it would be great to improve this code.

  • 写回答

2条回答 默认 最新

  • du1068 2019-02-27 09:45
    关注

    I'm not familiar with the Gate Facade but if it's in a model with relations, you can use whereHas :

    $users = App\User::whereHas('permissions', function ($q) use ($event) {
        $q->where('name', 'view')->where('model_id', $event->project->id);
    })->get();
    

    https://laravel.com/docs/5.7/eloquent-relationships#querying-relationship-existence

    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)