Laravel QueryBuilder - 执行查询前挂钩
Laravel QueryBuilder - hook before a query is executed
我想在执行前更改查询,例如
Event::listen('which event?', function($query) {
$query->where('foo', 'bar');
});
这样 Example::where('name', 'baz')->get()
就会产生这个 sql 代码:
select * from example where name = 'baz' and foo = 'bar'
.
这可能吗?
这通常最好在您的模型上使用 global scope 来处理。
Sometimes you may wish to define a scope that applies to all queries performed on a model. In essence, this is how Eloquent's own "soft delete" feature works. Global scopes are defined using a combination of PHP traits and an implementation of Illuminate\Database\Eloquent\ScopeInterface.
我想在执行前更改查询,例如
Event::listen('which event?', function($query) {
$query->where('foo', 'bar');
});
这样 Example::where('name', 'baz')->get()
就会产生这个 sql 代码:
select * from example where name = 'baz' and foo = 'bar'
.
这可能吗?
这通常最好在您的模型上使用 global scope 来处理。
Sometimes you may wish to define a scope that applies to all queries performed on a model. In essence, this is how Eloquent's own "soft delete" feature works. Global scopes are defined using a combination of PHP traits and an implementation of Illuminate\Database\Eloquent\ScopeInterface.