I really can't figure it out although it's fairly simple... I've got two tables: orders and revenues and I want to add a global scope to my Order model to load the sum of its paid revenues as an attribute. I tried joining and selecting the sum but nothing seems to change. The closest I've come to building the query was the following:
static::addGlobalScope('withPaidFromCustomer', function($builder){
$builder->leftJoin(DB::raw('select order_id, is_paid, sum(price) as paid_from_customer FROM revenues'), function($j){
$j->on('revenues.order_id', '=', 'orders.id')->where('revenues.is_paid', true);
});
});
I hope it's clear. I just want to get the paid_from_customer attribute in my model after querying. Thansk in advance!
@ADCADE - Thank you for the suggestion, I do actually already have an attribute getter set up for the purpose. Didn't think whether the $appends clause would change anything but it appears (as stated in the documentation) that it only modifies the loaded model serialization to array (adds the custom attributes), so it can't affect the query builder.
P.S. Sorry I really had forgotten to mention in my thread that I need this for query builder's sake. That's why I wanted to use a global scope in order to have selected the aggregate for extended queries for the Order model. So I really don't need anything related to the loaded model instance here, it's all about query optimization.
EDIT: Question remains unanswered, a query workaround and more complex raw expressions solved the issue.