在方法保护的引导模型 Laravel 中获取$this



>我的模型上有代码:

 protected static function boot() {
      parent::boot();
      if($this->status == 1) {
         static::updated(function () {
            //do something
         }
      }
 }

我需要检查当前记录的状态是否 == 1,然后执行static::updated().现在我得到错误:$this不能处于静态函数中。

如何检查受保护静态函数启动中的状态?

就像Daan在评论中提到的那样,这是不可能的,但是您可以通过另一种方式解决此问题:

protected static function boot() {
      parent::boot();
      static::updated(function ($model) {
          if ($model->status == 1) {
              //do something
          }
      });
 }

1( $this的用法

你应该用self::替换$this来引用静态类中包含的变量($status(:

 protected static function boot() {
      parent::boot();
      if(self::$_status == 1) {
         static::updated(function () {
            //do something
         }); //also close off your method call correctly.
      }
 }

2( 检查当前记录的状态是否 = 1

我需要检查当前记录的状态是否 == 1,然后执行静态::update((。

设置/保存/可访问$status的值在哪里?您显示的代码似乎表明$status是在类本身中设置的,但作为静态类,这将是静态的。

您可能需要停止类/方法的静态状态,或者像这样向函数提供数据:

 protected static function boot($status = null) {
      parent::boot();
      if($status == 1) {
         static::updated(function () {
            //do something
         }); // close off your method properly.
      }
 }

最新更新