【问题标题】:Laravel - Show users from the last 30 daysLaravel - 显示过去 30 天的用户
【发布时间】:2018-08-26 19:11:24
【问题描述】:

我有一个像这样的 Laravel 查询

$users = DB::table("users")
                   ->select('id')
                   ->where('accounttype', 'standard')
                   ->get()->all();

它正在工作并返回所有标准帐户的 ID,我试图将其限制为仅返回过去 30 天的结果,用户创建日期作为时间戳存储在“created_at”中

最好在查询中执行此操作还是应该在之后处理结果?

【问题讨论】:

  • 最好在查询中这样做。否则,当您拥有大量用户时,它不会很好地扩展。
  • 在您可以链接到我的查询中是否有任何示例?

标签: laravel laravel-5


【解决方案1】:

您可以将碳与where 子句一起使用:

use Carbon\Carbon;

$users = DB::table("users")
    ->select('id')
    ->where('accounttype', 'standard')
    ->where('created_at', '>', now()->subDays(30)->endOfDay())
    ->all();

如 cmets 中所述,在查询中尽可能多地执行操作,直到您发现性能问题或查询变得不可读。

【讨论】:

  • @MahediHasanDurjoy 如果帐户来自未来,那么是的,您的查询也可能有效
  • 我建议使用where 而不是whereDate,因此生成的SQL 查询可以受益于日期列上的任何索引。不过,必须更改代码以比较 23:59:59 的时间。
  • @miken32 我很久以前写了这个答案,所以我有点模糊。对于使用“>”或“
  • 是的,索引用于所有比较操作。 DATE(created_at) > '2018-03-17' 不能使用索引,因为它是派生值——必须为表中的每一行运行该函数。 created_at > '2018-03-17 23:59:59' 使用原始列值及其索引。
  • @miken32 - 谢谢 - 我已经更新了答案。有趣的是我认为whereDate 只是附加了->toDateTimeString() 而没有别的(即我认为这只是一种方便的方法)
【解决方案2】:

你可以使用它

\App\Model::whereBetween('date', [now()->subdays(30), now()->subday()])->get();

【讨论】:

    【解决方案3】:

    你可以使用它

    <?php
        namespace App\Http\Controllers;
        
        use App\User;
        use Illuminate\Http\Request;
        use Carbon\Carbon;
        
        class tblUserController extends Controller
        {     
        public function getSixtyMonthUser(){         
                $date = Carbon::today()->subDays(60);
                $users = User::where('created_at','>=',$date)
                ->where('accounttype', 'standard')
                ->select('id')
                ->get();
                return response()->json($users,200);
            
            }
        }
    

    【讨论】:

      【解决方案4】:

      这对我有用

          $thirty_days_ago = date('Y-m-d',strtotime("-31 days")); 
          $users_thirty_days_ago = User::where('accounttype', 'standard')->whereDate('last_online', ">=" , $thirty_days_ago)->count(); 
      

      【讨论】:

      • 对这个 3.5 年前的问题的其他答案有何改进?还请格式化您的代码,以确保可以在没有水平滚动的情况下尽可能阅读它。
      • 所有其他答案都在使用碳。这个答案没有。有些人不喜欢使用库
      • 问题标记为laravel
      • 我的回答也来自 Laravel。如果你仔细观察,你会看到与 eloquent 一起使用的 User 模型。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-28
      • 1970-01-01
      • 2012-03-01
      • 2020-06-29
      • 2013-05-19
      • 1970-01-01
      相关资源
      最近更新 更多