代码之家  ›  专栏  ›  技术社区  ›  Mr Robot

Laravel-如何从数据库中获取最后5个日期

  •  2
  • Mr Robot  · 技术社区  · 7 年前

    我有一个模型 ImportantDate 架构如下所示

    Schema::create('important_dates', function (Blueprint $table) {
        $table->increments('id');
        $table->date('date');
        $table->text('description');
        $table->timestamps();
        $table->softDeletes();
    });
    

    我想得到:

    1) 当前日期(今天)后的最后五个日期和

    2) 自当前日期起的未来五天(今天)

    样本数据:

    id    Date          description
    1     2017-12-20    some description
    2     2017-12-25    some description
    3     2018-01-02    some description
    4     2018-01-28    some description
    5     2018-02-02    some description
    6     2018-02-12    some description
    7     2018-02-18    some description
    8     2018-02-28    some description
    9     2018-03-02    some description
    10    2018-03-12    some description
    

    在我的 ImportantDatesController.php 我尝试了一个显示当前日期的最近日期的查询,但我需要从今天开始的最后5个日期和接下来的5个日期。

    public function index() 
    {
        $upcoming_dates = ImportantDate::orderByRaw(' abs( timestampdiff(second, current_timestamp, created_at)) asc ')
                                        ->limit(5)
                                        ->get();
    
        $recent_dates = ImportantDate::orderByRaw(' abs( timestampdiff(second, current_timestamp, created_at)) dsc ')
                                        ->limit(5)
                                        ->get();
    
        return view('pages.dashboard', compact('upcoming_dates','recent_dates'));
    }
    

    期待急需的帮助。

    非常感谢。

    3 回复  |  直到 7 年前
        1
  •  3
  •   Sohel0415    7 年前

    您可以使用 where() 第条至 compare 你的约会对象是 upcoming 日期或 previous 日期然后您可以使用 orderBy() 根据您的日期获取最新的5。

    $upcoming_dates = ImportantDate::where('date','>', date('Y-m-d'))->orderBy('date')
                                    ->limit(5)
                                    ->get();
    
    $recent_dates = ImportantDate::where('date','<', date('Y-m-d'))->orderBy('date', 'DESC')
                                    ->limit(5)
                                    ->get();
    
        2
  •  1
  •   Abdulla Nilam    7 年前

    DATE('Y-m-d') 将以给定格式给出当前日期。如果需要获取当前日期顶部,可以使用add >= <=

    $upcoming_dates = ImportantDate::where('date' , '>', DATE('Y-m-d'))
                        ->orderBy('id', asc)
                        ->limit(5)
                        ->get();
    
    $recent_dates = ImportantDate::where('date', '<', DATE('Y-m-d'))
                        ->orderBy('id', desc)
                        ->limit(5)
                        ->get();
    
        3
  •  1
  •   vivek manavadariya    7 年前
    SELECT * 
    FROM table
    WHERE id IN (SELECT id FROM table WHERE datetime = (SELECT MAX(datetime) FROM table))
    ORDER BY id DESC
    LIMIT 1