繁体   English   中英

一对多关系船(laravel)的总价

[英]Sum price of one to many relation ship (laravel)

我有一对多关系的问题! 所以我尝试总结产品价格,所以这就是我的意思:

型号: Product.php

/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function orders(){
    return $this->hasMany(Order::class);
}

模型: Orders.php

/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function product(){
    return $this->belongsTo(Product::class);
}

所以我想像这样: $var->product->price->sum();

如果需要,我的数据库:

订单: id product_id|user_id| |-|----------|-------| |1|1 |1 | | | | | id product_id|user_id| |-|----------|-------| |1|1 |1 | | | | |

并且产品只有 4 列: id,name,price,description

我的意思是:

 products:

  id\1

  name\productname

  price \1.00USD

  id\2

  name\productname2

  price \1.00USD

它必须返回所有产品的总和,所以它必须返回 2.00USD

@乔纳斯·施陶登迈尔

试试这个 QueryBuilder 查询:

 DB::table('orders')
    ->leftJoin('products','orders.product_id','=','products.id')
    ->where('orders.user_id',Auth::user()->id)
    ->select('orders.*','products.*',DB::raw("SUM(products.price) as order_total"))
    ->groupBy('orders.product_id')
    ->get();

我找到解决方案! 所以我做到了

我使用像之前一样的当前关系船,并在我的 order.php模型中创建该函数

public function getTotalPrice() {

$orders = self::with('product')->get();

$total = 0;

foreach($orders as $order) {
 $total += $order->product->price;
} 

return $total;
}

现在我可以像 obj 一样使用我的函数并将其称为$var->getTotalPrice();

在 Laravel 6+ 中我们可以这样使用,非常简单

$total = $order->product->sum('price');

使用没有DB eloquent 模型

Product::with(['orders' => function($query){
   $query->sum('price');
}])->get();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM