You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现特定用户当日数据筛选及食品日志当日记录展示

解决食品日志系统的当日数据筛选问题

嘿,这问题其实不难搞定!你已经能拿到用户的全量数据了,只需要在查询里加个日期筛选条件就能缩窄到当日(或指定日期)的记录。我给你一步步拆解:

基础实现:默认展示当日记录

直接修改你FoodlogController.php里的show方法,给查询添加whereDate条件,匹配记录的创建日期(假设你的Post模型用created_at字段存储记录时间):

public function show() {
    $userId = Auth::user()->id;
    // 筛选出当前用户今日创建的所有Post记录
    $posts = Post::where('user_id', $userId)
        ->whereDate('created_at', today())
        ->get();
    return view('foodlog', compact('posts'));
}

这里的today()是Laravel自带的辅助函数,会返回当前日期的Carbon实例,whereDate方法会自动忽略时间部分,只匹配日期,完美符合你“仅展示当日记录”的需求。

进阶:支持用户按指定日期检索

如果要实现用户自主选择日期查看的功能,只需要接收请求里的日期参数,动态调整筛选条件:

use Illuminate\Http\Request;

public function show(Request $request) {
    $userId = Auth::user()->id;
    // 获取用户提交的日期,默认显示今日
    $targetDate = $request->input('date', today()->toDateString());
    
    $posts = Post::where('user_id', $userId)
        ->whereDate('created_at', $targetDate)
        ->get();
    
    // 把选中的日期传递到视图,方便回显
    return view('foodlog', compact('posts', 'targetDate'));
}

然后在你的foodlog.blade.php视图里加个日期选择表单,让用户能提交指定日期:

<form method="GET" action="{{ route('foodlog.show') }}">
    <label for="date">选择日期:</label>
    <input type="date" id="date" name="date" value="{{ $targetDate }}">
    <button type="submit">查看记录</button>
</form>

<!-- 下面是展示当日食品条目的代码 -->
@foreach($posts as $post)
    <div class="food-item">
        <!-- 输出食品信息,比如名称、数量等 -->
        <h3>{{ $post->food_name }}</h3>
        <p>数量:{{ $post->quantity }}</p>
    </div>
@endforeach

补充说明

  • 如果你的Post模型不是用created_at存储日志日期,而是自定义了比如log_date字段,只需要把whereDate里的字段名改成对应的即可,比如whereDate('log_date', $targetDate)。
  • 如果你需要更精确的时间范围筛选(比如从当日00:00到23:59:59),可以用whereBetween替代whereDate:
    $start = today()->startOfDay();
    $end = today()->endOfDay();
    $posts = Post::where('user_id', $userId)
        ->whereBetween('created_at', [$start, $end])
        ->get();
    

这样就能完美实现你要的“按日期检索并查看当日记录”的功能啦!

内容的提问来源于stack exchange,提问作者GemmaM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:57:21