【问题标题】:How to get a list of all users which pass a specific policy?如何获取通过特定策略的所有用户的列表?
【发布时间】:2019-02-27 09:07:59
【问题描述】:

添加项目后,我会获取所有有权查看该项目的用户通知他们。
这发生在侦听器中:

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);
});

这行得通。但是,当我的系统中有 1000 个用户并且 5 个能够查看该项目时,我会毫无意义地迭代超过 995 个用户。
并且由于事件和监听器同步运行,添加项目的用户必须等待这一点发生。

我怎样才能加快这个速度?

编辑:好的,可以将侦听器排队。但是,改进此代码会很棒。

【问题讨论】:

  • 请您出示您的保单代码吗?
  • 我知道你要问这个问题了。我可以看看这个政策的逻辑,并用它来加速这个过程。但是当政策发生变化时,人们可能会忘记更新这一点。错误传入。
  • 好吧,根据您的政策中的逻辑,我将提出一些建议,但如果已经知道这无济于事,那就没关系了 :)
  • 项目的东西其实只是一个例子。我有多个侦听器需要找到要通知的用户。我有具有权限的组,并且大多数时候策略会检查用户是否具有权限。但正如我所说,当添加附加条件时,事情会变得很危险..

标签: php laravel authorization


【解决方案1】:

我对 Gate Facade 不熟悉,但如果它在具有关系的模型中,您可以使用 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

【讨论】:

    【解决方案2】:

    您可以使用 laravel 的 Notifications 特征来允许订阅用户接收通知事件。这些通知可以排队等待稍后处理,通过电子邮件/短信/松弛发送,保存到数据库,或用于广播消息,如您的用例。

    发出新通知

    php artisan make:notification InvoicePaid

    使用 notifiable 特征

    <?php
    
    namespace App;
    
    use Illuminate\Notifications\Notifiable;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    
    class User extends Authenticatable
    {
        use Notifiable;
    }
    

    现在用户有一个 notify 方法,该方法将 notification 作为参数

    use App\Notifications\InvoicePaid;
    
    $user->notify(new InvoicePaid($invoice));
    

    https://laravel.com/docs/5.8/notifications

    教程:https://code.tutsplus.com/tutorials/notifications-in-laravel--cms-30499

    【讨论】:

    • 谢谢,但这并不能解决我的问题。问题是找出应该通知哪些用户。
    • 哦,我明白了。我误解了这个问题。所以这是数据库设计问题,而不是 laravel 问题?您是否尝试过为具有 user_id 作为外键的通知创建表? $notifable_users = Notification::select('user_id')->get();
    猜你喜欢
    • 2019-03-21
    • 2019-01-02
    • 2013-10-05
    • 1970-01-01
    • 1970-01-01
    • 2019-11-09
    • 1970-01-01
    • 2020-12-27
    • 1970-01-01
    相关资源
    最近更新 更多