Laravel 自定义 Eloquent 方法

Laravel Custom Eloquent Method

我一直在构建查询和重复代码,有没有办法将其构建到 eloquent 模型中?

我有一个模型 Transaction,我在其中选择特定货币。如何将其添加到模型中?有没有办法改变这个:

Transaction::select('*')->where('currency', '=', 'GBP')

所以我可以这样做:

Transaction::select('*')->currency('GBP')

然后在模型中它以某种方式添加到查询中。我尝试创建 Transaction::currency 但没有成功。这只是一个示例,我计划添加一些选择器以保持代码整洁。

class Transaction extends Model
{
    protected $table = 'transactions';


    public function currency($query, $currency) {
      return $query->where('currency', '=', $currency);
    }
}

你快完成了,你必须将货币方法写为查询范围。

public function scopeCurrency($query, $currency) {
  return $query->where('currency', '=', $currency);
}

完成后你可以像这样使用作用域

Transaction::select('*')->currency('GBP')

点击此处了解更多详情https://laravel.com/docs/5.2/eloquent#local-scopes

Laravel 有一个叫做 Query Scopes 的东西。它使您可以完全按照自己的意愿行事。您只需要在 currency() 方法前加上 scope 关键字,如下所示:

class Transaction extends Model
{
    protected $table = 'transactions';


    public function scopeCurrency($query, $currency) {
      return $query->where('currency', '=', $currency);
    }
}

那你可以这样做Transaction::select('*')->currency('GBP')

阅读有关作用域的更多信息here

您可以使用范围来完成此操作。

将这些代码添加到 Transaction.php 文件

public function scopeCustom($query, $column, $exp, $value)
{
    return $query->where('votes', $exp, $value);  // ('currency', '=', 'GBP')
}

现在像这样使用这个范围

Transaction::select('*')->custom('currency', '=', 'GBP');
Transaction::select('*')->custom('amount', '>', 1000);