我有一个名为(TicketModel)的模型Eloquent,
我为一个用户添加了一个全局范围来获取所有票证,但有时,我想在没有这个范围的情况下使用票证,怎么办?如何忽略这个范围
这是型号
<?php
class TicketModel extends Eloquent{
public $timestamps = false;
public static function boot()
{
static::addGlobalScope(new TicketScope);
}
}
use Illuminate'Database'Eloquent'Builder;
use Illuminate'Database'Eloquent'ScopeInterface;
class TicketScope implements ScopeInterface {
public function apply(Builder $builder)
{
$builder->where('user_id', '=', Auth::user()->id_user);
}
public function remove(Builder $builder){}
}
为您需要作用域的情况提供一个子类怎么样?
这里有一个例子:
class TicketModel extends Eloquent
{
// Your model stuff here
}
class UserTicketModel extends TicketModel
{
public static function boot()
{
static::addGlobalScope(new TicketScope);
}
}
这个想法不是有时忽略范围,而是在你需要的时候使用它
如果您真的想让没有作用域的模型成为例外,那么让SimpleTicketModel
从TicketModel
继承并重写boot()
方法,这样它就不会使用作用域,如下所示:
class TicketModel extends Eloquent
{
public static function boot()
{
static::addGlobalScope(new TicketScope);
}
}
class SimpleTicketModel extends TicketModel
{
public static function boot()
{
// Do nothing else
}
}