在 laravel 5 的静态函数中调用非静态函数

call a non static function in a static function in laravel 5

我正在使用 laravel 5。在模型中,我有一个在控制器中调用的静态函数。它工作正常,但我希望此函数与另一个非静态函数进行相同的更改,当我在静态函数中调用它时会产生错误。

Non-static method App\Models\Course::_check_existing_course() should not be called statically

这是我的模型

namespace App\Models;
use Illuminate\Database\Eloquent\Model;

    class Course extends Model {
        public $course_list;
        protected $primaryKey = "id";
        public function questions(){
            return $this->belongsToMany('App\Models\Question','course_questions')->where("status",1)->orderBy("id","DESC");
        }

        public static function courses_list(){
            self::_check_existing_course();
        }
        private function _check_existing_course(){
            if(empty($this->course_list)){
                $this->course_list = self::where("status",1)->orderBy("course")->get();
            }
            return $this->course_list;
        }
    }

您将您的方法定义为非静态方法,但您正试图将其作为静态方法调用。

  1. 如果要调用静态方法,应使用 :: 并将方法定义为静态方法。

  2. 否则,如果您想调用实例方法,您应该实例化您的 class,使用 ->

    public static function courses_list() { $courses = new Course(); $courses->_check_existing_course(); }

通过阅读您的代码,您试图做的是将查询结果缓存到您的对象上。

有几种方法可以使用 Cache facade (https://laravel.com/docs/5.2/cache)

来解决这个问题

或者如果您只想在这种特定情况下为该请求缓存它,您可以使用静态变量。

class Course extends Model {
    public static $course_list;
    protected $primaryKey = "id";

    public function questions(){
        return $this->belongsToMany('App\Models\Question','course_questions')->where("status",1)->orderBy("id","DESC");
    }

    public static function courses_list(){
        self::_check_existing_course();
    }

    private static function _check_existing_course(){
        if(is_null(self::course_list) || empty(self::course_list)){
            self::course_list = self::where("status",1)->orderBy("course")->get();
        }

        return self::course_list;
    }
}