我需要为模型using the newQuery()
method创建默认的全局范围。
Laravel在Eloquent中记录say that it's possible以使用匿名函数对WHERE条件进行分组:
DB::table('users')
->where('name', '=', 'John')
->orWhere(function($query)
{
$query->where('votes', '>', 100)
->where('title', '<>', 'Admin');
})
->get();
但是当我在一个重载的newQuery()
方法中尝试时,我遇到了一些奇怪的事情。例如,假设我想这样做:
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
public function newQuery()
{
return parent::newQuery()->where(function($query) {
$query->where('foreign_id', MyClass::$id)->orWhere('role', 'admin');
});
}
我收到了502 Bad Gateway错误!我可以弄清楚如何在该方法中执行复合WHERE的唯一方法是执行原始查询:
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
public function newQuery()
{
return parent::newQuery()
->whereRaw('(foreign_id = ? or role = ?)')
->setBindings( array( MyClass::$id, 'admin' ) );
}
有谁知道为什么Eloquent会发生这种情况? It looks like someone else had a slightly different issue with Eloquent in that same method,但没有明确的答案。
答案 0 :(得分:1)
你需要全球范围。
以下是一个基本示例(有关框架附带的更多信息浏览器SoftDeletingScope
和SoftDeletingTrait
):
// Model
class PopularUser extends User {
protected $table = 'users';
public static function boot()
{
parent::boot();
static::addGlobalScope(new PopularUserScope);
}
}
// Scope
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\ScopeInterface;
class PopularUserScope implements ScopeInterface {
public function apply(Builder $builder)
{
$builder->where('votes', '>', 100)
->where('title', '<>', 'Admin');
}
public function remove(Builder $builder) { // you don't need this in your case }
}