在Laravel中从多个关系中汇总数据。

huangapple go评论101阅读模式
英文:

sum data from multiple relation in multiple relation in laravel

问题

我有一个User模型,拥有多个categories,而category拥有多个posts,post拥有一个Product。

现在我想要计算所有**Auth::user()**的product->price的总和。

我应该如何使用Laravel中的withSumwithCount函数来实现这个目标。

英文:

I have a User model, who hasMany categories and category hasMany posts and post hasOne Product

Now I want to sum all of the product->price of Auth::user()

how can i do that withSum or withCount function. in Laravel

答案1

得分: 2

以下是翻译好的内容:

由于您的问题没有提供任何细节,我将假设您已经正确设置了所有关系。

您可以使用以下方式使用关系来获取总和:

  1. $sum = Product::query()
  2. ->whereHas('post', function($post) {
  3. $post->whereHas('category', function($category) {
  4. $category->whereHas('user', function($user) {
  5. $user->where('id', auth()->id());
  6. });
  7. });
  8. })
  9. ->sum('price');

请注意,这是PHP代码,用于计算总和,假设您已正确设置了模型之间的关系。

英文:

Since your question doesnt present any details, I will assume that you have all the relations well set up.

You can get the sum using the relations like this

  1. $sum = Product::query()
  2. ->whereHas('post', function($post) {
  3. $post->whereHas('category', function($category) {
  4. $category->whereHas('user', function($user) {
  5. $user->where('id',auth()->id());
  6. });
  7. });
  8. })
  9. ->sum('price');

huangapple
  • 本文由 发表于 2023年2月19日 04:28:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75496201.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定