2

我正在使用 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;
        }
    }
4

2 回答 2

5

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

有几种方法可以使用 Cache 外观来解决这个问题(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;
    }
}
于 2016-04-02T14:58:23.550 回答
3

您将您的方法定义为非静态的,并尝试将其作为静态调用。

  1. 如果你想调用一个静态方法,你应该使用::并将你的方法定义为静态的。

  2. 否则,如果你想调用一个实例方法,你应该实例化你的类,使用->

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

于 2016-04-02T14:05:53.997 回答