問題描述
我覆蓋了 create()
Eloquent 方法,但是當我嘗試調用它時,我得到 Cannot make static method Illuminate\Database\Eloquent\Model::create() 類 MyModel 中的非靜態
.
I'm overriding the create()
Eloquent method, but when I try to call it I get Cannot make static method Illuminate\Database\Eloquent\Model::create() non static in class MyModel
.
我像這樣調用 create()
方法:
I call the create()
method like this:
$f = new MyModel();
$f->create([
'post_type_id' => 1,
'to_user_id' => Input::get('toUser'),
'from_user_id' => 10,
'message' => Input::get('message')
]);
在 MyModel
類中,我有這個:
And in the MyModel
class I have this:
public function create($data) {
if (!NamespaceAuth::isAuthed())
throw new Exception("You can not create a post as a guest.");
parent::create($data);
}
為什么這不起作用?我應該改變什么才能讓它工作?
Why doesn't this work? What should I change to make it work?
推薦答案
正如錯誤所說:IlluminateDatabaseEloquentModel::create()
方法是靜態的,不能被重寫為非靜態.
As the error says: The method IlluminateDatabaseEloquentModel::create()
is static and cannot be overridden as non-static.
所以實現它
class MyModel extends Model
{
public static function create($data)
{
// ....
}
}
并通過 MyModel::create([...]);
您也可以重新考慮 auth-check-logic 是否真的是模型的一部分,或者更好地將其移至控制器或路由部分.
You may also rethink if the auth-check-logic is really part of the Model or better moving it to the Controller or Routing part.
更新
這種方法從 5.4.* 版本開始不起作用,而是按照 這個答案.
This approach does not work from version 5.4.* onwards, instead follow this answer.
public static function create(array $attributes = [])
{
$model = static::query()->create($attributes);
// ...
return $model;
}
這篇關于擴展/覆蓋 Eloquent 創建方法 - 不能使靜態方法非靜態的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!