我有一个表模式,如下所示:
+----+---------------+------------+--------+
| id | crowd_fund_id | email | amount |
+----+---------------+------------+--------+
| 1 | 11 | jj@xx.com | 200 |
| 2 | 11 | sd@ff.com | 250 |
| 3 | 12 | jj@xx.com | 150 |
| 4 | 12 | abc@cc.com | 230 |
+----+---------------+------------+--------+和一个Entries表:
+----+---------+----------+------+
| id | user_id | crowd_id | name |
+----+---------+----------+------+
| 1 | 6 | 11 | Abc |
| 2 | 6 | 12 | Xyc |
| 3 | 8 | 18 | ijn |
+----+---------+----------+------+在面包师的模型中
public function entry()
{
return $this->belongsTo('App\Entries', 'crowd_fund_id', 'crowd_id');
}在控制器中,我调用了:
$var = Backers::with('entry')->where('email', $user->email)->get();这可以很好地工作。现在,我也想通过热切加载来获得sum。这意味着我需要调用类似于
Backers::with('entry')->with('sum')->where('email', $user->email)->get();sum将计算所有amount的总和,其中crowd_fund_id等于原始where email = $user->email。这意味着当我调用
Backers::with('entry')->with('sum')->where('email', $user->email)->get();我应该得到:
1 raw用于crowd_fund_id的支持者的详细信息
1 raw表示对应的条目,其中crowd_fund_id = crowd_id
1所有amount的总和,其中crowd_fund_id = crowd_fund_id来自支持者的详细信息。
我怎么才能得到这个呢?
发布于 2015-08-19 01:51:42
你能不能试一下(在你的支持者模型中):
public function backersSum()
{
return $this->hasOne('App\Backer')
->selectRaw('crowd_fund_id, sum(amount) as aggregate')
->groupBy('crowd_fund_id');
}这样做可以让你像任何关系一样急切地加载它。然后你可以这样做来访问它:
public function getBackersSumAttribute()
{
if ( ! $this->relationLoaded('backersSum'))
$this->load('backersSum');
$related = $this->getRelation('backersSum');
return ($related) ? (int) $related->aggregate : 0;
}https://stackoverflow.com/questions/32078892
复制相似问题