Php 拉维尔习惯口才法
我一直在构建查询和重复代码,有没有办法将其构建到雄辩的模型中 我有一个模型Php 拉维尔习惯口才法,php,laravel,eloquent,Php,Laravel,Eloquent,我一直在构建查询和重复代码,有没有办法将其构建到雄辩的模型中 我有一个模型交易,我在其中选择特定的货币。如何将其添加到模型中?有没有办法改变这一点: Transaction::select('*')->where('currency', '=', 'GBP') 这样我就可以做到: Transaction::select('*')->currency('GBP') 然后在模型中,它以某种方式添加到查询中。我试图创建Transaction::currency,但没有成功。这只是一个示
交易
,我在其中选择特定的货币。如何将其添加到模型中?有没有办法改变这一点:
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);
}
}
您几乎完成了,您必须编写currency方法作为查询范围
public function scopeCurrency($query, $currency) {
return $query->where('currency', '=', $currency);
}
这样做之后,您可以像这样使用范围
Transaction::select('*')->currency('GBP')
有关更多详细信息,请访问此处Laravel有一种称为查询范围的东西。它允许你做你想做的事情。您只需要在
currency()
方法前面加上scope关键字,如下所示:
class Transaction extends Model
{
protected $table = 'transactions';
public function scopeCurrency($query, $currency) {
return $query->where('currency', '=', $currency);
}
}
然后您可以执行此操作Transaction::select('*')->currency('GBP')
阅读有关作用域的更多信息您可以使用作用域来完成此操作 将这些代码添加到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);
创建事务服务,并在其中编写查询以从表中获取数据;我知道我在那里走对了路。谢谢你