首页 > 解决方案 > 如何通过具有不同的数据透视表对列求和 - Laravel/Eloquent

问题描述

我正在创建一个慈善资助申请跟踪器。资助申请可以有两个阶段。每个阶段可能由多个用户编写。

我的表设置如下:

用户(简化)

Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->string('first_name');
    $table->string('last_name');
    $table->string('email')->unique();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
 });

应用程序(简化)

Schema::create('applications', function (Blueprint $table) {
    $table->id();
    $table->foreignId('client_id');
    $table->foreignId('funder_id');
    $table->decimal('requested', 11, 0);
    $table->string('status');
    $table->decimal('stage_2_requested', 11, 0)->nullable();
    $table->string('stage_2_status')->nullable();
    $table->decimal('raised', 11, 0)->nullable();
    $table->timestamps();
 });

application_user(belongsToMany 与附加枢轴列“stage”的关系)

Schema::create('application_user', function (Blueprint $table) {
    $table->primary(['application_id', 'user_id', 'stage']);
    $table->bigInteger('application_id')->unsigned();
    $table->bigInteger('user_id')->unsigned();
    $table->integer('stage')->unsigned();
    $table->foreign('application_id')->references('id')->on('applications');
    $table->foreign('user_id')->references('id')->on('users');
 });

由于用户可能在数据透视表上多次链接到同一个应用程序,因此在计算聚合查询时,我需要获取不同的应用程序。

对于我的用户查询,我可以获得每个用户提交的唯一应用程序的数量以及成功的数量:

User::query->withCount([
    'applications as total_applications_submitted' => function ($query) {
        $query->select(
            DB::raw('
                count(distinct application_id)
             ')
         );
     },
     'applications as total_applications_successful' => function ($query) {
          $query->select(
              DB::raw('
                  count(distinct application_id)
              ')
          )
          ->where([['status', 'Successful'], ['stage_2_status', null]])
          ->orWhere('stage_2_status', 'Successful');
     },
])

我想得到的是每个用户从他们编写的应用程序中筹集的总金额,无论他们何时参与。

执行以下查询会聚合所有引发的列值,包括重复项(即用户在第一阶段和第二阶段编写的位置)。

User::query->withCount([
    'applications as total_raised' => function ($query) {
        $query->select(
            DB::raw('
                sum(raised)
             ')
         );
     },

我需要编写什么查询,它只能从不同的应用程序中获得总和?我不能做 sum(distinct raise) 例如,筹集的金额可能不是唯一的。

标签: mysqllaraveleloquent

解决方案


推荐阅读