0

I've got a simple Eloquent model (Player), and I simply want to add a bit of data to the returned data - the sum of all points awarded to the player in question Here's what I'm doing:

<?php

use Illuminate\Database\Eloquent\SoftDeletingTrait;

class Player extends \Eloquent {

    use SoftDeletingTrait;

    protected $fillable = [];
    protected $table = 'players';


    public function points_to_date()
    {
        return $this->hasMany('AwardedAction', 'player_id', 'id')->selectRaw('sum(points) as points');
    }
}
?>

Here's the reply I'm getting (note how points_to_date is null):

{
    "data": [
        {

            "id": 1,
            "player_id": "wooly",
            "created_at": "2014-09-18 16:35:30",
            "updated_at": "2014-09-18 16:35:30",
            "deleted_at": null,
            "points_to_date": null

        }
    ],
    "elapsed": 0.022357940673828
}

I'm running a profiler on the SQL queries and seeing this query:

select sum(points) as points from "awarded_actions" 
where "awarded_actions"."deleted_at" is null 
and "awarded_actions"."id" in (1)

.. so the query is running (and if I run it in the DB, it returns a value for the query, so it works), but not returning any data.

Has anyone tried to get L4 Eloquent to eager load and return an aggregated value as an attribute of the returned model data?

ArkadePaulG
  • 161
  • 2
  • 10

1 Answers1

2

You need to always select primary key and foreign key of the relation, otherwise Eloquent won't be able to match related models.

For what you want do this:

public function points_to_date()
{
    return $this->hasMany('AwardedAction', 'player_id', 'id')
       ->selectRaw('player_id, sum(points) as points')
       ->groupBy('player_id');
}
Jarek Tkaczyk
  • 78,987
  • 25
  • 159
  • 157