laravel 如何检查数组中的id是否超过出现次数

46scxncf  于 2023-03-09  发布在  其他
关注(0)|答案(1)|浏览(84)

我将要检查数组中的ID是否没有超过另一个字段的总出现次数。
数据库记录示例

sponsorship_items表格

| 身份证|标题|斑点|
| - ------|- ------|- ------|
| 1个|发起人1|第二章|
| 第二章|发起人2|五个|

user_sponsorships表格

| 身份证|赞助ID|
| - ------|- ------|
| 1个|1个|
| 第二章|1个|
| 三个|第二章|
初始Laravel代码:

public function compare()
{
  $userSponsorship = UserSponsorship::selectRaw('sponsorship_id, count(*) AS total_sponsors')
                            ->groupBy('sponsorship_id')
                            ->get();
  // more codes here...

}

输入示例:

$input = [1, 2]; // sponsorship_id

预期:

$response = [
   "sponsor1" => 0, // since there are only 2 available spots
   "sponsor2" => 4, // since there are 5 spots for sponsor2 and only one occured
];

如何根据上面的示例数据获得准确的响应?

jjhzyzn0

jjhzyzn01#

基于"sponsorship_items"和"user_sponsorships"表,我已经找到了解决方案。
下面是代码:

$userSponsorship = UserSponsorship::selectRaw('sponsorship_id, count(*) AS total_sponsors')
    ->groupBy('sponsorship_id')
    ->get()
    ->keyBy('sponsorship_id');

return collect([1 => 'sponsor1', 2 => 'sponsor2'])
    ->mapWithKeys(function ($title, $id) use ($userSponsorship) {
        $spots = SponsorshipItem::find($id)->spots;
        $occurrences = $userSponsorship->get($id)->total_sponsors ?? 0;

        return [$title => max(0, $spots - $occurrences)];
    })
    ->toArray();
}

希望这对你有帮助。

相关问题