laravel - Laravel Eloquent:我应该从模型还是控制器中附加值?
问题描述
我有一个带有id
、name
和的模型cost
。
protected $table = 'has_costs';
protected $fillable = [
'id','name','cost'
];
然后我还使用 append 添加新列,cost_under
and cost_over
,它基本上是从成本进行简单计算。
protected $appends = ['cost_over','cost_under'];
我应该像这样在模型中进行计算:
public function getCostOverAttribute()
{
$costOver = (20/100)*cost;
return $this->attributes['over'] = $costOver;
}
public function getCostUnderAttribute()
{
$costUnder = (80/100)*cost;
return $this->attributes['under'] = $costUndr;
}
还是我应该在控制器中做它以保持更多的“MVC”?
实际的代码比这个例子更复杂,并且需要花费大量时间来考虑如何将每个值附加到复杂的 Eloquentwith
查询中。
解决方案
答案很简单。
将它们保留在您的模型中,因为如果您做得对:
- 然后,您可以在 Eloquent 查询中使用它们
- 您可以使用
$model->costUnder
- 如果您知道我的意思,控制器更像是“资源管理器”而不是“模型描述符”。
推荐阅读
- javascript - JS HTML:从数组中调用随机函数
- c# - Discord.Net SendMessageAsync 没有命令
- javascript - 在 jQuery 中定义时间?
- c# - ASP.NET Core WEB Api 连接到 JS
- react-native-android - 我该如何解决“可能的未处理承诺拒绝(id:0)”?
- django - Django 3 - 过滤中的 ORM“AND”逻辑
- python - WandB - 为什么图表中的“步骤”刻度与给定的计算方式不同?(Python)
- java - 为什么 WebFlux-WebClient 超时不起作用?
- python - python - 在代码中替换 pd.rolling_apply
- javascript - 外部 javascript 文件在 HTML 文件中不起作用