在Laravel中如何从数组中提取最新日期对应的记录
实现方案
有两种常用实现方式,你可以根据自己的业务场景选择:
方案1:查询阶段直接过滤(推荐,性能更优)
直接在SQL查询时完成过滤,不需要拉取全量数据,适合数据量较大的场景:
// 先查询最新的月度账单对应的起始日期 $latestBillMonth = DB::table('weekly_billing') ->where('bill_period', 'monthly') ->max('from_date'); // 主查询增加月份过滤条件 $wdata= DB::table('weekly_billing') ->join('customers', 'weekly_billing.customer_id', '=', 'customers.id') ->select('weekly_billing.*','customers.customer_name','customers.bill_period') ->where('weekly_billing.bill_period','monthly') ->where('weekly_billing.from_date', $latestBillMonth) ->get();
如果你的from_date字段存在非每月1号的情况,可以替换最后一个where条件为年月匹配:
->whereRaw('DATE_FORMAT(weekly_billing.from_date, "%Y-%m") = DATE_FORMAT(?, "%Y-%m")', [$latestBillMonth])
方案2:集合处理(适合已获取全量数据的场景)
如果你已经拉取了全量的账单数据需要做其他业务处理,也可以直接用Laravel集合的内置方法过滤:
// 已获取全量数据 $wdata= DB::table('weekly_billing') ->join('customers', 'weekly_billing.customer_id', '=', 'customers.id') ->select('weekly_billing.*','customers.customer_name','customers.bill_period') ->where('weekly_billing.bill_period','monthly') ->get(); // 提取最新月份的所有记录 $latestMonth = $wdata->max(fn($item) => substr($item->from_date, 0, 7)); $latestMonthRecords = $wdata->filter(fn($item) => substr($item->from_date, 0, 7) === $latestMonth);
操作后$latestMonthRecords就是你需要的最新月份所有记录。
内容的提问来源于stack exchange,提问作者Mohammed
相关产品推荐
相关产品推荐

