使用Laravel

时间:2019-05-15 13:32:04

标签: 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(日期)选择最近的帐单记录,并在当前日期和{{1}之间的一个月内,选择用户名和created_at作为用户名}。请注意,每个用户名都会出现几次。

2 个答案:

答案 0 :(得分:0)

您可以尝试此操作以获取当月的数据:

$currentMonth = date('m');
$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])
      ->whereRaw('MONTH(billings.created_at) = ?',[$currentMonth])
       ->orderBy("billings.created_at", "desc")
       ->get(); 

或者,如果您想获取最近30天的数据,请尝试以下操作:

$date = \Carbon\Carbon::today()->subDays(30);
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])
       ->where('billings.created_at', '>=',$date)
       ->orderBy("billings.created_at", "desc")
       ->get(); 

答案 1 :(得分:0)

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

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

无论如何,如果您在需要处理复杂查询的地方使用这种DB结构,我极力建议您使用Eloquent和项目的面向对象结构。这样,只要像这样的段落^ _ ^,就可以避免查询。