PHP Laravel中如何根据key条件从集合中提取对应字段值?
完全可以实现,不需要重复执行数据库查询,Laravel查询构造器返回的Collection集合类内置了成熟的过滤操作方法,所有操作都在本地内存中执行,效率远高于重复发起数据库请求。
你可以直接使用集合的where()方法实现你要的效果,写法和查询构造器的where用法基本一致:
// 筛选所有考勤状态为Punch In的记录,返回集合类型 $timein = $todaylog->where('attendance_status', 'Punch In'); // 筛选所有考勤状态为End Break的记录,返回集合类型 $endbreak = $todaylog->where('attendance_status', 'End Break');
如果你只需要获取对应记录的timestamp字段值,不需要其他字段,可以配合pluck()方法使用:
// 提取所有Punch In记录的timestamp值 $timeinTimestamps = $todaylog->where('attendance_status', 'Punch In')->pluck('timestamp'); // 提取所有End Break记录的timestamp值 $endbreakTimestamps = $todaylog->where('attendance_status', 'End Break')->pluck('timestamp');
如果每个考勤状态只会对应一条记录,想要直接拿到timestamp的字符串值,可以用value()方法直接取第一个匹配的字段值:
$firstTimein = $todaylog->where('attendance_status', 'Punch In')->value('timestamp'); $firstEndbreak = $todaylog->where('attendance_status', 'End Break')->value('timestamp');
内容的提问来源于stack exchange,提问作者wenreloz
相关产品推荐
相关产品推荐

