問題描述
我試圖在我的控制器中加載我的模型并嘗試了這個:
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.
這篇關于為什么在調用 Eloquent 模型中的方法時出現“不應靜態調用非靜態方法"?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!