扩展/覆盖口才创建方法-无法使静态方法变为非静态 [英] Extend/override Eloquent create method - Cannot make static method non static

查看:49
本文介绍了扩展/覆盖口才创建方法-无法使静态方法变为非静态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我覆盖了create()雄辩的方法,但是当我尝试调用它时,我得到了Cannot make static method Illuminate\\Database\\Eloquent\\Model::create() non static in class 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()方法:

$f = new MyModel();
$f->create([
    'post_type_id' => 1,
    'to_user_id' => Input::get('toUser'),
    'from_user_id' => 10,
    'message' => Input::get('message')
]);

MyModel类中,我有这个:

public function create($data) {
    if (!Namespace\Auth::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?

推荐答案

正如错误所述:方法Illuminate\Database\Eloquent\Model::create()是静态的,不能被覆盖为非静态的.

As the error says: The method Illuminate\Database\Eloquent\Model::create() is static and cannot be overridden as non-static.

因此将其实现为

class MyModel extends Model
{
    public static function create($data)
    {
        // ....
    }
}

并通过MyModel::create([...]);

您还可以重新考虑auth-check-logic是否确实是模型的一部分,或者最好将其移至Controller或Routing部分.

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;
}

这篇关于扩展/覆盖口才创建方法-无法使静态方法变为非静态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆