为什么在调用 Eloquent 模型中的方法时出现“不应静态调用非静态方法"?

2021-12-26 00:00:00 php laravel eloquent

我试图在我的控制器中加载我的模型并尝试了这个:

Im trying to load my model in my controller and tried this:

return Post::getAll();

得到错误 非静态方法 Post::getAll() 不应静态调用,假设 $this 来自不兼容的上下文

模型中的函数如下所示:

The function in the model looks like this:

public function getAll()
{

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

}

在控制器中加载模型然后返回其内容的正确方法是什么?

What's the correct way to load the model in a controller and then return it's contents?

推荐答案

您已将方法定义为非静态方法,而您正试图以静态方式调用它.话说……

You defined your method as non-static and you are trying to invoke it as static. That said...

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

1.if you want to invoke a static method, you should use the :: and define your method as static.

// Defining a static method in a Foo class.
public static function getAll() { /* code */ }

// Invoking that static method
Foo::getAll();

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

2.otherwise, if you want to invoke an instance method you should instance your class, use ->.

// 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 方法都返回模型的一个实例,允许您按如下所示链接方法:

Note: In Laravel, almost all Eloquent methods return an instance of your model, allowing you to chain methods as shown below:

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

在该代码中,我们通过 Facade 静态调用 all 方法.之后,所有其他方法都被称为实例方法.

In that code we are statically calling the all method via Facade. After that, all other methods are being called as instance methods.

相关文章