0

I have a Laravel backend and a VueJS frontend.

I'm trying to produce a query on a model with a hasOne relationship but only select specific columns from the relationship, do a sum and a group by.

Models

  • Contract (CONTRACT_TYPE, CONTRACT_PRICE)
  • AdditionalInfo (START_DATE)

My Eloquent Query

public function contractsByYear() {
   return Contract::where('CONTRACT_TYPE','LIKE','SP-%')->with(['AdditionalInfo' => function($query) {
       $query->selectRaw('MONTH(START_DATE) as Month')->whereYear('START_DATE','2019');
   }])->sum('CONTRACT_PRICE')->groupBy('Month');
}

Expected Results

MONTH | TOTAL
1     | 500
2     | 233
3     | 800
etc

My issue is the table structure is existing and I can't edit. Why the START_DATe is stored in a separate table is beyond me.

1 Answer 1

0

Collection methods will probably do what you want

public function contractsByYear()
{
    return Contract::select('id', 'CONTRACT_PRICE') /* Only really need the id (or whatever else is the pk) and the price */
    ->where('CONTRACT_TYPE','LIKE','SP-%')
    ->with(['AdditionalInfo' => function($query) {
        $query->select('id', 'contract_id')         /* Only really need the id (or whatever else is the pk), and the Contract fk*/
        ->selectRaw('MONTH(START_DATE) as Month')   /* Aggregate the month */
        ->whereYear('START_DATE','2019');
    }])
    ->get()
    // From this point on, it's a Collection
    ->groupBy('AdditionalInfo.*.Month')             /* It's either this or 'AdditionalInfo.Month' */
    ->map(function($item, $key) {
        return [
            'month' => $key,
            'total' => $item->sum('CONTRACT_PRICE')
        ];
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.