【问题标题】:Getting the total count of a relationship tables results获取关系表结果的总数
【发布时间】:2021-05-06 00:45:50
【问题描述】:

您好,我正在尝试从我的数据库中获取投票计数结果,但不确定最佳方法。

主题模型

protected $fillable = [
    'division_id',
    'date',
    'title',
    'description',
    'aye_count',
    'noe_count'
];

public function votes()
{
    return $this->hasMany(Vote::class, 'topic_id', 'division_id');
}

投票模式

protected $fillable = [
    'topic_id',
    'user_id',
    'user_aye_count',
    'user_noe_count'
];

function topic() {
    return $this->belongsTo(Topic::class, 'topic_id', 'division_id');
}

我的控制器是这样的

public function filterTopicsByTitle(Request $request)
{

    $division_id = $request->get('filterTopicsByTitle');

    $topicResults = Topic::with(['votes'])->where('division_id', $division_id)->first();

    dd($topicResults->votes);

    return view('dashboard', compact('topicResults'));

}

转储输出以下内容

Illuminate\Database\Eloquent\Collection {#1259 ▼
  #items: array:2 [▼
    0 => App\Models\Vote {#1263 ▼
      +timestamps: false
      #fillable: array:4 [▶]
      #connection: "mysql"
      #table: "votes"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:5 [▼
        "id" => 1
        "user_id" => 2
        "topic_id" => 965
        "user_aye_count" => 1
        "user_noe_count" => null
      ]
      #original: array:5 [▶]
      #changes: []
      #casts: []
      #classCastCache: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      #hidden: []
      #visible: []
      #guarded: array:1 [▶]
    }
    1 => App\Models\Vote {#1265 ▼
      +timestamps: false
      #fillable: array:4 [▶]
      #connection: "mysql"
      #table: "votes"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:5 [▶]
      #original: array:5 [▼
        "id" => 5
        "user_id" => 1
        "topic_id" => 965
        "user_aye_count" => null
        "user_noe_count" => 1
      ]
      #changes: []
      #casts: []
      #classCastCache: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      #hidden: []
      #visible: []
      #guarded: array:1 [▶]
    }
  ]
}

我基本上需要用总数创建 2 个变量 $userAyeCount$userNoeCount。我能想到的唯一方法是使用 foreach 循环获取行 user_aye_count 或 user_noe_count 并递增变量。

这似乎不是正确的方法,当有大量或行时,我猜它会慢得多。任何帮助将不胜感激。

【问题讨论】:

  • 您需要对这些“求和”吗?因为 Eloquent 有一种基于关系计数或字段等进行聚合的方法

标签: laravel eloquent laravel-8


【解决方案1】:

我相信您需要针对特定​​主题的 user_aye_countuser_noe_count 的总数 如果是这种情况,您可以自定义 withCount 方法并执行聚合以汇总投票模型中所有相关记录的这些计数

 $topicResult = Topic::withCount([
                            'votes as aye_count' => function ($query) {
                                        $query->select(DB::raw("sum(user_aye_count)"));
                            },
                            'votes as noe_count' => function ($query) {
                                        $query->select(DB::raw("sum(user_noe_count)"));
                            },
                            'votes as total' => function ($query) {
                                        $query->select(DB::raw("sum(user_aye_count + user_noe_count)"));
                            }
                    ])->where('division_id', $division_id)
                      ->first();

Laravel 8 has now introduced withSumluxury 我猜你可以在查询生成器中添加多个withSum 子句

$topicResult = Topic::withSum('votes', 'user_aye_count')
                     ->withSum('votes', 'user_noe_count')
                     ->select(['topics.*', DB::raw('votes_sum_user_aye_count  + votes_sum_user_noe_count as total')])
                     ->first();

结果值可以被访问为

$topicResult->votes_sum_user_aye_count;
$topicResult->votes_sum_user_noe_count;
$topicResult->total;

【讨论】:

  • eloquent 现在有一个withSum 方法
  • @lagbox 感谢更新,不知道这个,让我搜索一下
  • 我接受了你的回答,因为它让我走上了正确的道路,我不需要总数,只需要赞成和反对。我似乎无法在评论中格式化它,但我只需要下面的代码$topicResults = Topic::withSum('votes', 'user_aye_count')->withSum('votes', 'user_noe_count') ->where('division_id', $division_id)->first();
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-11
  • 2014-05-06
  • 2012-04-07
  • 1970-01-01
  • 2015-12-04
  • 1970-01-01
相关资源
最近更新 更多