2016-04-02 17 views
1

私は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

あなたは非静的としてあなたの方法を定義している、あなたは、静的、それを起動しようとしています。あなたは、静的メソッドを呼び出したい場合は

  1. 、あなたは::を使用し、staticとしてあなたの方法を定義する必要があります。

  2. あなたはインスタンスメソッドを呼び出したい場合はそうでない場合、あなたはあなたのクラスのインスタンスをすべきでは、何をしようとするあなたのコードを読んでから->

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

+0

私はそれを試みましたが、静的関数$ this->は動作しませんでした。 – Jitendra

+0

私は自分の答えを編集しました。今すぐやってみて下さい。それは動作するはずです。 –

1

を使用するには、結果をキャッシュしていますあなたのオブジェクトに対するあなたの質問。

は、この使用に

キャッシュのファサード(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; 
    } 
} 
関連する問題