Laravel - 显示过去30天内的用户

时间:2018-03-17 22:14:21

标签: laravel laravel-5

我有一个看起来像这样的Laravel查询

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

它正在运行并返回所有标准帐户的ID,我试图将其限制为仅返回过去30天的结果,创建用户的日期存储为' created_at&#39中的时间戳;

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

3 个答案:

答案 0 :(得分:2)

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

use Carbon\Carbon;

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

如评论中所述,在您发现性能问题或查询变得不可读之前,请尽可能多地进行查询。

答案 1 :(得分:0)

您可以使用它

\App\Model::whereBetween('date', [
           \carbon\Carbon::now()->subdays(30)->format('Y-m-d'),
           \carbon\Carbon::now()->subday()->format('Y-m-d')
        ])->get();

答案 2 :(得分:0)

你可以使用它

<?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);
        
        }
    }
相关问题