我试图向Illuminate'Database'Eloquent'Collection
添加一个静态函数。
我尝试了以下方法:
创建了一个类:
class CustomCollection extends 'Illuminate'Database'Eloquent'Collection
{
public static function test()
{
die('test');
}
}
然后我尝试包括班级。
但是运气不好,我收到错误消息:Call to undefined method Illuminate'Database'Eloquent'Collection::test()
发出错误消息,呼叫User::where('id', 1)->get()->test();
若要使用集合而不是 Eloquent 提供的集合,请在模型中添加一个方法:
public function newCollection(array $models = [])
{
// of course, adjust your namespace accordingly
return new CustomCollection($models);
}
它将在类Illuminate'Database'Eloquent'Model
重写此方法:
/**
* Create a new Eloquent Collection instance.
*
* @param array $models
* @return 'Illuminate'Database'Eloquent'Collection
*/
public function newCollection(array $models = array())
{
return new Collection($models);
}
现在,每次 Eloquent 查询返回集合(例如,使用 YourModel::all()
)时,都将使用自定义集合,并且您添加的方法将可用。
来源: 拉拉维尔文档
由于我无法使用评论功能,我必须回答,尽管我觉得它不应该被标记为答案。您的错误指出您正在调用 Collection::test()。集合类中的方法测试不存在!您使用集合扩展了自定义集合,并向自定义集合添加了一个方法,而不是集合!