【问题标题】:laravel 4.2 and ignore global scopelaravel 4.2 并忽略全局范围
【发布时间】:2016-05-12 00:01:00
【问题描述】:

我有一个名为 (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){}

}

【问题讨论】:

    标签: php laravel laravel-4 eloquent


    【解决方案1】:

    对于需要范围的情况有一个子类怎么样?

    这是一个例子:

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

    【讨论】:

    • 但是我有超过15个模型,需要扩展所有类
    • 扩展课程是一项一次性任务。您需要在某个时刻对您的模型说您不需要范围。另一种方法是每次你想忽略范围时调用一个方法(在模型实例化之前),这意味着,可能在一个给定的脚本中多次......扩展类并不是什么大问题:一旦完成,它就完成了。你的模型有一个名字,这意味着它是什么。顺便说一句,您可以将它用于类型提示。
    • Laravel 5.2 容器允许 contextual binding,这在您的情况下可能很有用...但是 Laravel 4.2... :/
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    • 1970-01-01
    • 2015-12-02
    • 1970-01-01
    • 2015-07-06
    • 2023-03-09
    • 2011-11-12
    相关资源
    最近更新 更多