I have the relations user->sales->detail_sales, a user has one or many sales, a sale has one or more details. What I'm trying to do is obtain with ELOQUENT, the total of all sales per user, that is, make a sum(totaldetails) of the calculated total with withCount.
Sale.php
public function detail()
{
return $this->hasMany(Detail:class);
}
public function user()
{
return $this->belongsTo('App\User');
}
DetailSale
public function sale()
{
return $this->belongsTo(Sale::class);
}
User
public function sales()
{
return $this->hasMany(Sale::class );
}
This query I currently have
return App\User::with(['sales' => function($query){
// get total for detail_sales for sale
$query->withCount(['detail as totaldetails' => function($que){
$que->select(DB::raw('sum(subtotal)'));
}]);
}])->get();
but I want that in the User model, to have a property like salestotal for example, is it possible?
@foreach($users as $user)
{{ $user->salestotal}}
@endforeach
aslike$que->select(DB::raw('sum(subtotal) as salestotal'));salesanddetail_salesrelationships.subtotalcolumn lies, in thesalestable or in thedetailstable? could you share the tables structure with us please.