【问题标题】:Laravel Query Builder - Use sum method on a generated attributeLaravel 查询生成器 - 对生成的属性使用 sum 方法
【发布时间】:2017-07-21 02:59:24
【问题描述】:

假设我有这两个模型:

订购模式:

  • 身份证
  • 状态(不完整,完整)

物品型号:

  • 身份证
  • order_id
  • 类型
  • is_worthy。

.

/**
 * Returns the item's price according to its worthy
 */
public function getPriceAttribute()
{
    return $this->is_worthy ? 100 : 10; // $
}

到目前为止一切顺利。

现在我想总结一下完整订单的价格。所以我正在这样做:

App\Item::whereHas('order', function ($query) {
    $query->where('state', 'complete');
})->sum('price')

但问题是,我的items 表中没有price 列。因为price属性是在Model中生成的。

所以我的问题是,如何总结完整订单的价格?

【问题讨论】:

  • Laravel 有 whereType 吗?错误信息是什么?
  • @FatimahSanni Laravel 具有动态 where 方法,例如 whereXyz(xyz 是表的列名)

标签: php mysql laravel eloquent laravel-query-builder


【解决方案1】:

有两种方法可以做到这一点:

1.让 PHP 完成所有工作

$items = App\Item::whereHas('order', function ($query) {
    $query->where('state', 'complete');
})->get();
$sum = $items->sum(function($item) {
    return $item->price;
});
// In Laravel 5.4, you can replace the last line with $sum = $items->sum->price;

2。让 SQL 完成所有工作

$items = App\Item::whereHas('order', function ($query) {
    $query->where('state', 'complete');
})->select('*', DB::raw('IF(is_worthy, 100, 10) as price'))->sum('price');

【讨论】:

    【解决方案2】:

    Laravel

    型号

    /**
     * Returns the item's price according to its worthy
     */
    public function getPriceAttribute()
    {
        return $this->is_worthy ? 100 : 10; // $
    }
    

    控制器

    retrun OrderItem::where('state', 'complete')->get()->sum('price');
    

    【讨论】:

    • 虽然此代码可能会解决问题,including an explanation 关于如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请edit您的回答添加解释并说明适用的限制和假设。
    猜你喜欢
    • 2015-08-06
    • 2018-12-26
    • 2013-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-13
    • 2018-11-15
    • 1970-01-01
    相关资源
    最近更新 更多