扩展/覆盖 Eloquent 创建方法 - 不能使静态方法非静态

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

我覆盖了 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;
}

相关文章