每当我向Eloquent 的模型添加额外的逻辑时,我最终不得不将其设置为static个方法(即不太理想),以便从模型的外观调用它.我已经try 了很多关于如何以正确的方式实现这一点的搜索,几乎所有的结果都讨论了如何创建返回部分查询生成器界面的方法.我试图找出如何添加可以返回任何内容并使用模型的facade调用的方法.

For example, lets say I have a model called Car and want to get them all:

$cars = Car::all();

很好,除了现在,假设我想通过make将结果排序为多维数组,这样我的结果可能如下所示:

$cars = array(
  'Ford' => array(
     'F-150' => '...',
     'Escape' => '...',
  ),
  'Honda' => array(
     'Accord' => '...',
     'Civic' => '...',
  ),
);

以这个理论为例,我很想创建一个方法,可以像这样调用:

$cars = Car::getAllSortedByMake();

让我们暂时忘记这个可怕的方法名,以及它与数据 struct 紧密耦合的事实.如果我在模型中使用这样的方法:

public function getAllSortedByMake()
{
   // Process and return resulting array
   return array('...');
}

And finally call it in my controller, I will get this Exception thrown:

假设$this来自不兼容的上下文,则不应静态调用非静态方法Car::getAllSortedByMake()

TL;DR:我如何添加在模型中有意义的自定义功能,而不使其成为静态方法,并使用模型的facade调用它?


编辑:

This is a theoretical example. Perhaps a rephrase of the question would make more sense. Why are certain non-static methods such as all() or which() available on the facade of an Eloquent model, but not additional methods added into the model? This means that the __call magic method is being used, but how can I make it recognize my own functions in the model?

可能比"排序"更好的示例是,如果我需要对一段数据运行计算或算法:

$validSPG = Chemical::isValidSpecificGravity(-1.43);

对我来说,这样的东西出现在模型中是有意义的,因为它是特定于领域的.

推荐答案

My question is at m或e of a fundamental level such as why is all() accessible via the facade?

如果您看一下Laravel C或e-all()实际上是一个静电函数

public static function all($columns = array('*'))

您有两个 Select :

public static function getAllS或tedByMake()
{
    return Car::where('....')->get();
}

public function scopeGetAllS或tedByMake($query)
{
    return $query->where('...')->get();
}

两者都将允许您执行以下操作

Car::getAllS或tedByMake();

Laravel相关问答推荐

Laravel Livewire与自定义JS有关的多姆问题

laravel 如何验证跨越午夜的两个值之间的时间(15:00 > 时间 > 01:00)

Laravel 5 - 更改模型文件位置

在 laravel 5.3 中截断的错误日志(log)

Laravel Livewire 组件在刷新后不会自动刷新/重新加载

如何在 Laravel 5.5 中扩展 vendor 包服务提供者

升级到 laravel 5.4 后调用未定义的方法

如何创建具有关系的 Eloquent 模型?

Cookie::forget 不工作 laravel 5.1

WhereNotExists Laravel Eloquent

如果值存在于另一个字段数组中,Laravel 验证规则

验证匹配字符串

在 Laravel 测试用例中模拟一个 http 请求并解析路由参数

将 Laravel 集合附加到另一个集合

Laravel 在保存前生成 slug

Laravel 4:将什么作为参数传递给 Url 类?

如何在 Laravel 5 中的每个相关输入字段旁边显示验证错误?

Laravel 事件、监听器、作业(job)、队列之间的区别

如何在laravel中获取列值的平均值

将图像保存在公共文件夹中,而不是存储 laravel 5