我覆盖了 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模板网!
PHP、MySQL PDOException 的死锁异常代码?Deadlock exception code for PHP, MySQL PDOException?(PHP、MySQL PDOException 的死锁异常代码?)
PHP PDO MySQL 可滚动游标不起作用PHP PDO MySQL scrollable cursor doesn#39;t work(PHP PDO MySQL 可滚动游标不起作用)
PHP PDO ODBC 连接PHP PDO ODBC connection(PHP PDO ODBC 连接)
使用 PDO::FETCH_CLASS 和魔术方法Using PDO::FETCH_CLASS with Magic Methods(使用 PDO::FETCH_CLASS 和魔术方法)
php pdo 只从 mysql 获取一个值;等于变量的值php pdo get only one value from mysql; value that equals to variable(php pdo 只从 mysql 获取一个值;等于变量的值)
MSSQL PDO 找不到驱动程序MSSQL PDO could not find driver(MSSQL PDO 找不到驱动程序)