Laravel 获取用户所有付款的收入总和?

Laravel 获取用户所有付款的收入总和?,laravel,eloquent,Laravel,Eloquent,用户→ 有很多→ 书籍→ 有很多→ 订单→ 有许多付款 书中模型: 公共职能支付() { 返回$this->hasManyThrough(付款::类,订单::类); } 订单表 Schema::创建('orders',函数(Blueprint$表){ $table->bigIncrements('id'); $table->unsignedbiginger('user_id'); $table->unsignedbiginger('book_id'); $table->unsignedInte

用户→ 有很多→ 书籍→ 有很多→ 订单→ 有许多付款

书中模型:

公共职能支付()
{
返回$this->hasManyThrough(付款::类,订单::类);
}
订单表

Schema::创建('orders',函数(Blueprint$表){
$table->bigIncrements('id');
$table->unsignedbiginger('user_id');
$table->unsignedbiginger('book_id');
$table->unsignedInteger('amount');
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('book_id')->references('id')->on('books');
});
支付迁移:

Schema::创建('payments',函数(Blueprint$表){
$table->bigIncrements('id');
$table->unsignedbiginger('order_id');
$table->string('payment_method');
$table->unsignedInteger('author_-earning');
$table->foreign('order_id')->references('id')->on('orders');
});
}
我的问题:我想列出所有用户的所有图书付款的
作者收入的总和
。 我试着做一些类似的事情:

$users = User::with(['books.payments' => function ($query) {
            $query->sum('instructor_earning');
        }])
        ->whereHas('books.payments')
        ->get();

但是,没有运气。如何解决此问题?

因为当您使用具有许多关系的时,闭包需要获得雄辩的生成器列,至少包括外键,雄辩的使用此外键来创建嵌套集合

但是,sum将返回一个数字,而不是雄辩的列

因此,如果你将每本书的作者收入加起来,你可以使用accessor

这样做,, 书中模型:

protected$appends=['author_-earning'];
公共函数getAuthorEarningAttribute()
{
$sum=Book::where('books.id',$this->id)
->join('orders','orders.book_id','=','books.id')
->join('payments','payments.order_id','=','orders.id')
->groupBy('books.id')
->选择原始('books.id,SUM(payments.amount)作为SUM')
->第一个()->和;
返回$sum;
}
因此,当您使用图书付款方式时,如下所示:

[{"id":1,
  "username":"Tom",
  "books":[{
    "id":1,
    "title": "Tom and Jerry",
    "author_earning": 18,
    "orders": [{
      "id":1,
      "number": "FA00000001"
      "payments": [{"id":1,"author_earning":15},{"id":2,"author_earning": 3}]
    },{
    "id":2,
    "title": "Dragon Ball",
    "author_earning": 2,
    "orders": [{
      "id":2,
      "number": "FA00000002"
      "payments": [{"id":1,"author_earning":2}]        
    }]
  }]
}]      
$users=User::with(['books.payments'])
->whereHas(‘账簿、付款’)
->get()->toJson();
您将获得如下数据:

[{"id":1,
  "username":"Tom",
  "books":[{
    "id":1,
    "title": "Tom and Jerry",
    "author_earning": 18,
    "orders": [{
      "id":1,
      "number": "FA00000001"
      "payments": [{"id":1,"author_earning":15},{"id":2,"author_earning": 3}]
    },{
    "id":2,
    "title": "Dragon Ball",
    "author_earning": 2,
    "orders": [{
      "id":2,
      "number": "FA00000002"
      "payments": [{"id":1,"author_earning":2}]        
    }]
  }]
}]