문제

I have the following in my user module

// A user has many assets.
public function assets()
{
 return $this->belongsToMany('Asset');
}

In my controller I have:

$assetValue = User::find($id)->assets;

I only want to sum up the values from a single field from the records returned and pass it to a view.

I've tried using all sorts of SUM() calls and I am now stumped.

So something like this would be great

$assetValue = User::find($id)->assets->sum('values');

Thanks

Edit* The output of $assetValue = User::find($id)->assets;

[{"id":"1","name":"asset1","serial_num":"1234","value":"100.00","created_at":"2014-03-18 20:06:37","updated_at":"2014-03-18 20:06:37","pivot":{"user_id":"1","asset_id":"1"}},

{"id":"2","name":"asset2","serial_num":"5678","value":"200.00","created_at":"2014-03-18 20:06:37","updated_at":"2014-03-18 20:06:37","pivot":{"user_id":"1","asset_id":"2"}},

{"id":"3","name":"asset3","serial_num":"91011","value":"300.00","created_at":"2014-03-18 20:06:37","updated_at":"2014-03-18 20:06:37","pivot":{"user_id":"1","asset_id":"3"}}]
도움이 되었습니까?

해결책

User::find($id)->assets will give you a Eloquent\Collection which doesn't allow you to query the results as they've already been pulled from the database.

To access the Eloquent\Builder object which would allow you to query the results you need to use User::find($id)->assets()->sum('value');

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top