mysql - 如何将 Eloquent 查询转换为 Adonis lucid?
问题描述
所以我正在将 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();
此代码返回总和而不是总行数。
我在这里错过了什么吗?或者这超出了withCount
阿多尼斯的限制范围?
解决方案
推荐阅读
- python - 继承类属性而不声明属性或更好的 OOP
- jms - 如何使用 JMS 使用“其他”(不是 usr 区域)文件夹创建 MQRFH2 标头
- angular - 错误类型错误:无法读取未定义的属性“句柄”
- php - Laravel 密码重置导致 Swift_TransportException 错误
- servlets - Java Servlet,http 状态 404,请求的资源不可用
- bash - 重命名几个 gopro 文件
- gradle - java.lang.IllegalArgumentException:不支持的类文件主要版本 57
- python - 我可以在主函数中放置多少个函数?
- reactjs - 获得“不变违规:超过最大更新深度”。ImmerJS 出错
- django - 此站点无法提供安全连接 ERR_SLL_PROTOCOL ERROR