首页 > 解决方案 > 使用 Laravel 选择恰好一个月内最近的记录

问题描述

我正在加入 Laravel 中的两 (2) 个表 (usersbillings)。在计费表中,可以对用户进行多次计费。因此,这意味着用户名可以出现多次。我想根据created_at(日期)选择账单的最新记录,然后选择用户名和created_at.

我在 Laravel 中创建了一个选择查询。

$monthlysubscriptionupdate = DB::table("billings")
    ->select("billings.phone", "billings.email", "billings.plan", 
        "billings.created_at", "users.username",
        "users.msisdn", "users.auto_subscription")
    ->join("users", "users.username", "=", "billings.username")
    ->where(['users.package_id' => '1102', 'users.auto_subscription' => 0])
    ->get(); 

在计费表中,可以对用户进行多次计费。因此,这意味着用户名可以出现多次。我想根据created_at(日期)选择账单的最新记录,并created_at在当前日期和created_at. 请注意,每个用户名都会出现多次。

标签: laravel

解决方案


正如 Daniel Luna 所说,您可以使用 whereDate + orderBy 。whereDate 示例

$q->whereDate('created_at', '=', date('Y-m-d'));

无论如何,如果您在需要处理复杂查询的地方使用这种类型的数据库结构,我强烈建议您使用 Eloquent 和项目的面向对象结构。像这样你就可以避免查询,只要一个段落^_^ 喜欢这个。


推荐阅读