Programing

Eloquent 모델에서 메서드를 호출 할 때 '비 정적 메서드를 정적으로 호출해서는 안됩니다'라는 메시지가 나타나는 이유는 무엇입니까?

lottogame 2020. 11. 21. 08:21
반응형

Eloquent 모델에서 메서드를 호출 할 때 '비 정적 메서드를 정적으로 호출해서는 안됩니다'라는 메시지가 나타나는 이유는 무엇입니까?


내 컨트롤러에 내 모델을로드하려고 시도하고 이것을 시도했습니다.

return Post::getAll();

오류가 발생했습니다 Non-static method Post::getAll() should not be called statically, assuming $this from incompatible context

모델의 기능은 다음과 같습니다.

public function getAll()
{

    return $posts = $this->all()->take(2)->get();

}

컨트롤러에서 모델을로드 한 다음 내용을 반환하는 올바른 방법은 무엇입니까?


메서드를 비 정적으로 정의했고이를 정적으로 호출하려고합니다. 그건 ...

  1. ... 정적 메서드를 호출하려면을 사용하고 ::메서드를 정적으로 정의해야합니다.

    // Defining a static method in a Foo class.
    public static function getAll() { /* code */ }
    
    // Invoking that static method
    Foo::getAll();
    
  2. ... 그렇지 않으면 인스턴스 메서드를 호출하려면 클래스를 인스턴스화해야합니다 ->..

    // Defining a non-static method in a Foo class.
    public function getAll() { /* code */ }
    
    // Invoking that non-static method.
    $foo = new Foo();
    $foo->getAll();
    

참고 : Laravel에서 거의 모든 Eloquent 메서드는 모델의 인스턴스를 반환하므로 아래와 같이 메서드를 연결할 수 있습니다.

$foos = Foo::all()->take(10)->get();

이 코드에서 우리는 Facade를 통해 메서드를 정적으로 호출합니다 all. 그 후 다른 모든 메소드는 인스턴스 메소드 로 호출됩니다 .


스코프를 추가해보세요. 스코프는 Eloquent의 아주 좋은 기능입니다.

class User extends Eloquent {

    public function scopePopular($query)
    {
        return $query->where('votes', '>', 100);
    }

    public function scopeWomen($query)
    {
        return $query->whereGender('W');
    }

}

$users = User::popular()->women()->orderBy('created_at')->get();

Laravel Docs의 Eloquent #scopes


TL; DR . MyModel::query()->find(10);대신 쿼리를 표현하여이 문제를 해결할 수 있습니다 MyModel::find(10);.

내가 아는 한, 시작 PhpStorm 2017.2 코드 검사는 다음과 같은 방법 실패 MyModel::where(), MyModel::find()등 (이 확인 스레드 ). 코드를 커밋하기 전에 PhpStorm의 Git 통합 을 사용하려고하면 PhpStorm 이 이러한 정적 메서드 호출 경고에 대해 불평하는 것을 멈추지 않을 것입니다.

이 문제를 해결하는 우아한 방법 (IMOO) 중 하나 는 의미가있는 곳에 명시 적으로 호출::query() 하는 것입니다. 이렇게하면 무료 자동 완성과 멋진 쿼리 형식의 이점을 얻을 수 있습니다.

검사에서 정적 메서드 호출에 대해 불평하는 스 니펫

$myModel = MyModel::find(10); // static call complaint

// another poorly formatted query with code inspection complaints
$myFilteredModels = MyModel::where('is_beautiful', true)
    ->where('is_not_smart', false)
    ->get();

불만없이 잘 포맷 된 코드

$myModel = MyModel::query()->find(10);

// a nicely formatted query with no complaints
$myFilteredModels = MyModel::query()
    ->where('is_beautiful', true)
    ->where('is_not_smart', false)
    ->get();

Just in case this helps someone, I was getting this error because I completely missed the stated fact that the scope prefix must not be used when calling a local scope. So if you defined a local scope in your model like this:

public function scopeRecentFirst($query)
{
    return $query->orderBy('updated_at', 'desc');
}

You should call it like:

$CurrentUsers = \App\Models\Users::recentFirst()->get();

Note that the prefix scope is not present in the call.


You can give like this

public static function getAll()
{

    return $posts = $this->all()->take(2)->get();

}

And when you call statically inside your controller function also..


I've literally just arrived at the answer in my case. I'm creating a system that has implemented a create method, so I was getting this actual error because I was accessing the overridden version not the one from Eloquent.

Hope that help?


Check if you do not have declared the method getAll() in the model. That causes the controller to think that you are calling a non-static method.


For use the syntax like return Post::getAll(); you should have a magic function __callStatic in your class where handle all static calls:

public static function __callStatic($method, $parameters)
{
    return (new static)->$method(...$parameters);
}

참고URL : https://stackoverflow.com/questions/18339716/why-im-getting-non-static-method-should-not-be-called-statically-when-invokin

반응형