【问题标题】:Laravel Eloquent How to get Sum of relationship based on countLaravel Eloquent 如何根据计数获得关系总和
【发布时间】:2021-11-06 22:04:06
【问题描述】:

这是我的数据库表: 我有 3 个相互关联的表。

Table Companies
--------------
ID       TITLE

Table Customers
------------------------
ID    company_id    Name

Table Transactions
-----------------------------------------
ID    company_id    customer_id    amount

这是我的模特关系:

Model Relations:
Company:
hasMany(Customers)
hasMany(Transactions)

Customer Model:
belongsTo(Company)
hasMany(Tranactions)

Transactions Model:
belongsTo(Company)
belongsTo(Customer)

我需要获取仅包含 3 笔交易的客户交易“金额”的总和。

这是我的工作方式:

$query = Customer::select('id')->withCount([
    'transactions as transactions_count' => function ($query) use ($safe) {
          $query->where('amount', '>', 0);
     },
     'transactions AS transactions_sum' => function ($query) use ($safe) {
          $query->select(DB::raw("SUM(amount)"))->where('amount', '>', 0);
     }
])->having('transactions_count', 3);
$sql_with_bindings = \Str::replaceArray('?', $query->getBindings(), $query->toSql());

$result = DB::select("
        SELECT
            SUM(x.transactions_sum) as amount
        FROM
        (".$sql_with_bindings.") x
 ");

对更好的雄辩方式有什么建议吗?

【问题讨论】:

    标签: laravel eloquent relationship


    【解决方案1】:

    $count = Transactions::where('customer_id', 1)->count();

    如果($count == 3){ 你的参数 }

    【讨论】:

    • 请添加更多详细信息以扩展您的答案,例如工作代码或文档引用。
    【解决方案2】:

    DB::select("your_parameter")->limit(3);

    【讨论】:

    • 我不想限制结果。
    • 我有很多客户。现在我想获得只有 3 笔交易的客户的总金额。
    • 您好,欢迎来到 Stack Overflow!请拨打tour。另请查看help center 以获取有关如何格式化代码的信息。
    猜你喜欢
    • 2020-04-04
    • 2017-05-01
    • 1970-01-01
    • 2020-02-28
    • 2021-12-08
    • 2020-06-19
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    相关资源
    最近更新 更多