sql - Laravel 使用嵌套关系计算资源中的数量
问题描述
我有这个结构:
invoices
, invoices_lines
, invoices_lines_taxes
,taxes
关系:
invoices
与 是一对多的invoices_lines
。
invoices_lines
taxes
与中间表是多对多的invoices_lines_taxes
楷模:
Invoice
public function lines()
{
return $this->hasMany(InvoiceLine::class, 'invoice', 'id');
}
InvoiceLine
public function taxes()
{
return $this->belongsToMany(Tax::class, 'invoices_lines_taxes', 'line', 'tax');
}
资源:
InvoiceResource
public function toArray($request)
{
return [
'id' => $this->id,
'invoice_date' => $this->invoice_date,
'reference' => $this->reference,
'number' => $this->number,
'description' => $this->description,
'state' => $this->state,
'type' => $this->type,
'lines' => InvoiceLineResource::collection($this->whenLoaded('lines')),
'amount' => $this->whenLoaded('lines', function () {
return $this->lines()->sum(DB::raw('unit_price * quantity'));
}),
];
}
我设法计算了 InvoiceResource 上的金额。但我需要用税来计算这些金额。
我该怎么做?
public function toArray($request)
{
return [
'id' => $this->id,
'invoice_date' => $this->invoice_date,
'reference' => $this->reference,
'number' => $this->number,
'description' => $this->description,
'state' => $this->state,
'type' => $this->type,
'lines' => InvoiceLineResource::collection($this->whenLoaded('lines')),
'amount' => $this->whenLoaded('lines', function () {
return $this->lines()->sum(DB::raw('unit_price * quantity'));
}),
'amount_taxes' => ?????
];
}
我可以通过 SQL 进行这些查询来获得税收......但我怎样才能将它翻译成 Laravel 雄辩的方式?
select id from invoices -- get invoice_id.
select id from invoices_lines where invoice = $invoice_id -- get id of invoice_lines
select tax from invoices_lines_taxes where line = $invoice_line_id -- get the id of tax.
select rate from taxes where id = $tax_id
rate 是我必须乘以金额的浮点数(百分比)。所以表达式应该是:invoices_lines.unit_price
* invoices_lines.quantity
*taxes.rate
解决方案
推荐阅读
- r - 在包含嵌套括号的字符串中,如何使用 str_extract 获取整个括号?
- python - Django - 每次保存后上传图像()
- tailwind-css - 顺风配置中的基础用于什么?
- python - Binance Websocket客户端在一段时间后停止
- azure - 如何使用 REST API 在 Azure DevOps 中禁用分支策略?
- github-actions - Strapi 与 Github Actions - 保留公共上传
- swift - Swift:“FileHandle”类型的值在引用嵌套在 FileHandle 子类中的自定义函数时没有成员,但扩展工作正常
- sql - dplyr vs dbplyr 过滤与空白
- authentication - Schoology API:从另一个平台使用 Schoology 登录
- pine-script - 错误消息:参数的类型应为:series[float]