【问题标题】:Laravel Eloquent: Should I append values from the model or controller?Laravel Eloquent:我应该从模型还是控制器中附加值?
【发布时间】:2019-07-16 11:09:26
【问题描述】:

我有一个带有idnamecost 的模型。

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

然后我还用append添加了新的列,cost_undercost_over,基本上都是从cost做简单的计算。

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”?

实际的代码比这个例子更复杂,需要花费大量时间考虑如何在复杂的 Eloquent with 查询中附加每个值。

【问题讨论】:

    标签: laravel model-view-controller eloquent model append


    【解决方案1】:

    cost_overcost_under添加为模型属性更有意义。

    public function getCostOverAttribute()
    {
        return 20 / 100 * $this->cost;
    }
    
    public function getCostUnderAttribute()
    {
        return 80 / 100 * $this->cost;
    }
    

    您可以通过$model->cost_over$model->cost_under 访问它们。

    保持您的控制器不受内部模型对其数据的计算影响。

    此外,如果您不想在每次实例化模型时附加这些属性,您可以在控制器中附加属性为 $model->append('cost_over')

    【讨论】:

      【解决方案2】:

      答案很简单。

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

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

      【讨论】:

        猜你喜欢
        • 2017-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-12
        • 1970-01-01
        • 2012-11-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多