首页 > 解决方案 > 如何将 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阿多尼斯的限制范围?

标签: mysqlnode.jsexpressadonis.js

解决方案


推荐阅读