Laravel在方法启动后有条件地添加全局范围 [英] Laravel conditionally add global scopes after method boot

查看:49
本文介绍了Laravel在方法启动后有条件地添加全局范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在模型已经通过构造函数之后,是否可以添加全局作用域?

Is it possible to add a global scope after the model has already passed the constructor?

我想捕获一个事件(例如 creating )并仅在创建模型时才附加全局作用域.

I would like to catch an event (for example creating) and attach a global scope only if the model is creating.

到目前为止,我已经完成:

So far I've done:

Event::listen('eloquent.creating*', function ($event, $model) {
    /**
     * @var Model $eloquentModel
     */
    $eloquentModel = $model[0];
    $eloquentModel->addGlobalScope(new AuthorizationScope($event));
});

调用了作用域构造函数,但从未触发过它的 apply 方法,因为此时的模型显然已经通过了触发作用域的部分.我该如何手动将其发射?

The scope constructor is called, but the apply method from it is never fired because the model at that point already obviously passed the part where it fires the scopes. How could I manually fire it?

推荐答案

tl; dr;这不可能.在Eloquent事件触发时,作用域已经加载并应用.

tl;dr; It is not possible. At the time when the Eloquent events are firing scopes are already loaded and applied.

用例:我想在模型创建/编辑/删除上添加其他范围以能够进行某种动态授权,但这是无效的,因为Laravel使用Eloquent查询构建器来执行DB SELECT .对于其他所有内容(例如插入或删除),将形成一个不同的查询,并且该查询未连接到给定的查询生成器,因此即使您可以使用它,也没有任何意义,因为它将形成一个单独的查询以进行创建/无论如何/删除操作.

Use case: I wanted to add additional scopes on model create/edit/delete to be able to do some sort of dynamic authorization, however this is not valid because Laravel uses Eloquent query builder for doing DB SELECT. For everything else, such as inserts or deletes, a different query is formed and is not connected to a given query builder, so even if you could tap into it, it makes no sense to do it as it would form a separate query for create/edit/delete actions anyways.

我最终要做的是重用我在范围内使用的逻辑,但是我不会在开始时限制查询(范围会做什么),而是在事件侦听器中进行检查并返回 true / false (取决于该检查).

What I ended up doing was reusing the logic which I used within scopes, but instead of limiting the query initially (what scopes do), I would do my checks within event listener and return true/false depending on that check.

对于这个具体示例,在捕获 eloquent.creating 事件时返回 false 意味着将不会创建模型,这正是我所需要的.

For this concrete example, returning false upon catching eloquent.creating event would mean that the model will not be created, which is exactly what I needed.

有关更多详细信息,请随时检查微服务授权包我使用这种方法开发的.

For any more details, feel free to check authorization package for microservices I developed using this approach.

这篇关于Laravel在方法启动后有条件地添加全局范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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