Php Laravel查询生成器-对生成的属性使用求和方法
假设我有以下两种型号: 订单型号:Php Laravel查询生成器-对生成的属性使用求和方法,php,mysql,laravel,eloquent,laravel-query-builder,Php,Mysql,Laravel,Eloquent,Laravel Query Builder,假设我有以下两种型号: 订单型号: 身份证 状态(不完整、完整) 项目型号: 身份证 订单号 类型 这是值得的 到目前为止还不错 现在我想总结一下完整订单的价格。所以我要这样做: App\Item::whereHas('order', function ($query) { $query->where('state', 'complete'); })->sum('price') 但问题是,我的items表中没有price列。因为price属性是在模型中生成的
- 身份证
- 状态(不完整、完整)
项目型号:
- 身份证
- 订单号
- 类型
- 这是值得的
到目前为止还不错 现在我想总结一下完整订单的价格。所以我要这样做:
App\Item::whereHas('order', function ($query) {
$query->where('state', 'complete');
})->sum('price')
但问题是,我的items
表中没有price
列。因为price
属性是在模型中生成的
所以我的问题是,如何总结完整订单的价格?有两种方法: 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');
有两种方法可以做到这一点: 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');
拉雷维尔有何型号?错误消息是什么?@FatimahSanni Laravel有动态where方法,比如whereXyz(xyz是表的列名)Laravel有where类型吗?错误消息是什么?@FatimahSanni Laravel有动态where方法,如whereXyz(xyz是表的列名)