【问题标题】:Extend/override Eloquent create method - Cannot make static method non static扩展/覆盖 Eloquent 创建方法 - 不能使静态方法非静态
【发布时间】:2013-10-16 12:56:24
【问题描述】:

我正在重写 create() Eloquent 方法,但是当我尝试调用它时,我得到了 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);
}

为什么这不起作用?我应该改变什么才能让它工作?

【问题讨论】:

    标签: php laravel laravel-4 eloquent


    【解决方案1】:

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

    所以实现它

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

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

    您还可以重新考虑 auth-check-logic 是否真的是模型的一部分,或者更好地将其移至控制器或路由部分。

    更新

    此方法从 5.4.* 版本开始不再适用,请遵循 this answer

    public static function create(array $attributes = [])
    {
        $model = static::query()->create($attributes);
    
        // ...
    
        return $model;
    }
    

    【讨论】:

    • 我给了这个“重新思考”声明+1!此逻辑不属于 MyModel 类。
    【解决方案2】:

    可能是因为您正在覆盖它并且在父类中它被定义为static。 尝试在函数定义中添加单词static

    public static function create($data)
    {
       if (!Namespace\Auth::isAuthed())
        throw new Exception("You can not create a post as a guest.");
    
       return parent::create($data);
    }
    

    当然,您还需要以静态方式调用它:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-16
      • 1970-01-01
      • 1970-01-01
      • 2018-06-21
      • 2012-11-07
      • 2011-11-16
      相关资源
      最近更新 更多