首页 文章

Laravel:从时间戳读取可用的月份和年份以填充<SELECT>

提问于
浏览
1

我有一个电影表,其中有一个时间戳列CREATED_AT . 格式是:

name            created_at
Pocahontas      2016-12-28 22:09:24

我知道如何从当前月份添加的表中选择电影

$year_month_film = DB::table('films')
        ->select('films.*')
        ->whereMonth('films.created_at', '=', Carbon::now()->month)
        ->orderBy('films.created_at', 'desc')
        ->get();

但现在我想让用户动态选择任何一年中任何一个月添加的电影列表(见图):

Selected all films from december 2016

我在HTML视图中构建了两个,以便动态选择任何一年中任何一个月添加的电影 .

<div class="pull-right">
            <select>
              <option value="all" selected>Months</option>
              <option value="January">January</option>
              <option value="February">February</option>
              <option value="March">March</option>
              ...
            </select>              
            <select>
              <option value="all" selected>Years</option>
              <option value="2011">2011</option>
              <option value="2014">2014</option>
              <option value="2016">2016</option>
              ...
            </select> 
        </div>

问题是:

  • 我没有每个月和每年都添加电影,因此我需要通过阅读"created_at"列来了解数据库中存在哪些月份和哪些年份(彼此独立) . 然后传递给视图 . 但我不知道如何使用Carbon来做到这一点 .

  • 我如何获取所选的月份和年份,然后传递给控制器并进行动态搜索,而不仅仅是我在开始时发布的当前月份?

EDIT:

只是为了更新可能有用的人:我已经删除了重复的月份,在Yohanan Baruchel分配的代码中添加了一行代码,代码现在看起来像这样:

$available_years_with_months = [];

        $all_year_and_months = DB::table('films')
           ->select('*')
           ->orderBy('films.created_at', 'desc')
           ->get()->each(function($film) use (&$available_years_with_months) {
             $date = Carbon::parse($film->created_at);
             $year = $date->format('Y');
             $month = $date->format('F');
             $available_years_with_months[$year][] = $month;
            $available_years_with_months[$year] = array_unique($available_years_with_months[$year]);

           });

2 回答

  • 0

    如果您只想获得实际拥有电影的月份列表,您可以使用我为您编写的下一行:

    $available_years_with_months = [];
    
    $all_year_and_months = DB::table('films')
           ->select('*')
           ->get()->each(function($film) use (&$available_years_with_months) {
             $date = Carbon::parse($film->created_at);
             $year = $date->format('Y');
             $month = $date->format('F');
             $available_years_with_months[$year][] = $month;
           });
    
  • 1

    Springtf的变更编号范围为2 .

    $year_month_film = DB::table('films')
        ->select('*')
        ->whereMonth('created_at', '=', sprintf("%02d",Carbon::now()->month))
        ->orderBy('films', 'desc')
        ->get();
    

相关问题