所以我要将Laravel应用重写为Adonis应用,这是我的模型
// A customer can have multiple invoices
class Customer extends Model {
invoices() {
return this.hasMany('App/Models/Invoice');
}
invoiceItems() {
return this.manyThrough('App/Models/Invoice', 'items');
}
}
// An invoice can have multiple invoice items
class Invoice extends Model {
items() {
return this.hasMany('App/Models/InvoiceItem');
}
customer() {
return this.belongsTo('App/Models/Customer');
}
}
// An invoice item belongs to an invoice
class InvoiceItem extends Model {
product() {
return this.belongsTo('App/Models/Product');
}
invoice() {
return this.belongsTo('App/Models/Invoice');
}
}
我想获取发票价格*数量的总和,这是我的 / api / customers
的示例输出Customer.query()
.withCount('invoiceItems as invoice_items_total', builder => {
builder.select(
DB.raw('sum(price * quantity)')
);
})
.fetch()
[
{
"id": 2,
"account_no": "Solana-2",
"type": "person",
"first_name": "Mark",
"middle_name": "",
"last_name": "Soriano",
"company_name": "",
"address": "Solana",
"created_at": "2019-12-08 10:22:12",
"updated_at": "2019-12-08 10:24:09",
"__meta__": {
"invoice_items_total": 1, // Still returns total no. of rows instead of sum(product * quantity) ?
}
}
]
这很奇怪,而不是DB.raw('sum(price * quantity)')
的值,我仍然得到的是invoice_items行的总数为1。
我的laravel代码如下所示,并且可以正常工作:
Customer::withCount([
'invoice_items as invoice_items_total' => function($query) {
$query->select(DB::raw('sum(price * quantity)'));
},
])->get();
此代码返回总和而不是总行数。
我在这里错过了什么吗?还是超出了Adonis中withCount
约束的范围?任何帮助将不胜感激。