2014-09-18 44 views
0

我有一个简单的Eloquent模型(玩家),我只是想添加一点数据到返回的数据 - 所有点的总和授予有问题的球员这里是我在做什么:Laravel 4急于加载聚合SUM不工作 - 查询运行但不返回?

<?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'); 
    } 
} 
?> 

这里是我得到的答复(注意points_to_date如何为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 
} 

我运行在SQL查询分析器,看到这个查询:

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

..所以查询正在运行(如果我在数据库中运行它,它将返回查询值,因此它可以工作),但不返回任何数据。

有没有人试图让L4 Eloquent进行急切加载并返回一个聚合值作为返回的模型数据的属性?

回答

2

您需要始终关联select primary key and foreign key,否则Eloquent将无法匹配相关模型。

对于要做到这一点的:

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

完美亚雷克 - 非常感谢的是,它会帮助我在未来的好方法。 – ArkadePaulG 2014-09-19 14:12:07

+0

你也可以看看这个:http://softonsofa.com/tweaking-eloquent-relations-how-to-get-latest-related-model/ – 2014-09-19 14:17:17