Jit*_*dra 2 php static-methods static-functions laravel-5
我正在使用 laravel 5。在模型中,我有一个静态函数,我在控制器中调用它。它工作正常,但我希望这个函数与另一个非静态函数进行相同的更改,当我在静态函数内调用它时,它会产生错误。
Non-static method App\Models\Course::_check_existing_course() should not be called statically
Run Code Online (Sandbox Code Playgroud)
这是我的模型
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;
}
}
Run Code Online (Sandbox Code Playgroud)
通过阅读代码,您想要做的是将查询结果缓存在对象上。
有几种方法可以使用缓存外观(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;
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8600 次 |
最近记录: |