Home > database >  New column from calculating 2 other eager columns Laravel
New column from calculating 2 other eager columns Laravel

Time:01-13

I get 2 numbers made through withCount in my Eloquent query result. Is there any way to multiply/divide/add these 2 numbers and make a new field?

$data = Trek::select('name')
            ->withCount('past_bookings')
            ->withCount('bookings')
            ->get();

(Like ->select(DB::raw('past_bookings*bookings as new_col'))??)
When I used an accessor, I got Call to a member function addEagerConstraints() on int error.

CodePudding user response:

You could also do it via another step. Like that:

$collection = Trek::select('name')
            ->withCount('past_bookings')
            ->withCount('bookings')
            ->get();

$data = [];
foreach($collection as $item) {
    $data['past_bookings_count/bookings as new_col'] = ($item['past_bookings'] / $item['bookings_count']);
}


dd($data);

However, if this is passed on to a view, I would leave the loop and carry out the calculation in the view.

.blade.php

{{ $data['past_bookings_count'] / $data['bookings_count'] }}

CodePudding user response:

Are you really need new column? You can do on your model;

public function getMyCalculationAttribute()
{
    return $this->past_bookings_count * $this->bookings_count;
}

you can access it like this:

$trekModel->my_calculation;

you can look official docs

  •  Tags:  
  • Related