首页 > 解决方案 > Laravel Eloquent:我应该从模型还是控制器中附加值?

问题描述

我有一个带有idname和的模型cost

protected $table = 'has_costs';
protected $fillable = [
    'id','name','cost'
];

然后我还使用 append 添加新列,cost_underand 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查询中。

标签: laravelmodel-view-controllereloquentmodelappend

解决方案


答案很简单。

将它们保留在您的模型中,因为如果您做得对:

  • 然后,您可以在 Eloquent 查询中使用它们
  • 您可以使用$model->costUnder
  • 如果您知道我的意思,控制器更像是“资源管理器”而不是“模型描述符”。

推荐阅读