我尝试使用此模型获取结果
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
列的总和以及其他详细信息吗?或者是否有其他方法?
答案 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();