【发布时间】:2018-05-18 15:49:29
【问题描述】:
我有 Book 和 Store 模型,它们具有 belongsToMany 关系。
在 Book.php 中
public function stores(){
return $this->belongsToMany('App\Store')->withPivot('qty');
}
在 Store.php 中
public function books(){
return $this->belongsToMany('App\Book')->withPivot('qty');
}
现在我只想知道 A 店和 B 店的图书总数。我怎样才能用雄辩的 ORM 做到这一点?我可以使用 whereHas 获取属于商店 A 和 B 的所有书籍,但无法进一步聚合数据透视表中的 qty 字段。
【问题讨论】:
-
你想知道A、B的店铺数量和每本书的总数量吗?请进一步解释
-
@SapneshNaik 例如,商店 A 有 2 个 book-a 和 3 个 book-b。商店 B 有 3 个 book-a 和 4 个 book-b 所以结果是 book-a: 5 book-b: 7
标签: laravel eloquent laravel-eloquent