如何在Laravel 5.6中使用具有hasMany结果的SUM()

时间:2018-08-09 04:52:32

标签: eloquent

我尝试使用此模型获取结果

HH:mm a

我的控制器功能是这个

use Illuminate\Database\Eloquent\Model;
use DB;
class Customer_Bones extends Model
{
  protected $table = 'customer_bones';
  protected $primaryKey = 'customer_bones_id';
  protected $fillable = array(
    'created_at',
    'deleted',
    'system_user',
    'customer_id',
    'bones_id'
);
public $timestamps = false;

public function getBonusCustomers(){

    return $this->hasMany('App\Models\Bonus_Item','customer_bones_id');

}

public function getCustomer(){
    return $this->hasOne('App\Models\Customer','customer_id');
}
}

我想从return Customer_Bones::with(array( 'getCustomer' => function($query) { $query->select('customer_name','customer_id'); }, 'getBonusCustomers' => function($query) { $query->select(DB::raw('sum(bonus_quantity) as bonusQuantity')); })) ->get(); 表中获取bonus_quantity表所属的Bonus_Item列的customer_name列的总和,并从customer表中获取一些其他详细信息。我曾尝试过上述方法,但customer_bones返回null。

我可以像上面一样在bonusQuantity内使用DB::raw('sum(bonus_quantity) as bonusQuantity')来获取select clause列的总和以及其他详细信息吗?或者是否有其他方法?

1 个答案:

答案 0 :(得分:1)

您可以在回调中使用withCount和原始表达式来获取所需的总和,例如

Customer_Bones::with(['getCustomer' => function($query){
                                          $query->select('customer_name','customer_id');
                                       }
])->withCount(['getBonusCustomers as bonusQuantity' => function($query) {
                                                            $query->select(DB::raw('SUM(bonus_quantity)'));
                                                        }
])->get();

或者您可以在模型中定义一个新的映射,该映射将按customer_bones_id

返回总和
public function getBonusCustomersSum(){

    return $this->hasOne('App\Models\Bonus_Item','customer_bones_id')
                ->select('customer_bones_id',DB::raw('sum(bonus_quantity) as bonusQuantity'))
                ->groupBy('customer_bones_id');
}

Customer_Bones::with(['getCustomer' => function($query){
                                          $query->select('customer_name','customer_id');
                                       }
, 'getBonusCustomersSum'])
->get();

Laravel use multiple where and sum in single clause