首页 > 解决方案 > 如何在 Laravel 5.5 中创建按日期分组的两个模型的集合?

问题描述

我有两个模型TourAdventure. 我想做一组按日期分组的旅行和冒险。并像这样显示它:

7 月 17 日

游览 1 游览 2 游览 3 冒险 1 冒险 2 冒险 3

7 月 16 日

游览 1 游览 2 游览 3 冒险 1 冒险 2 冒险 3

我知道如何对单个模型进行分组。它是这样的:

Tour::orderBy('created_at', 'desc')->take(20)->get()->groupBy(function($item)
          {
            return $item->created_at->format('d-M-y');
          });

如何加入这两个模型并将它们显示在一个日期中?与当前代码天出现在不同的集合中。

编辑:包括表迁移。

public function up()
    {
        Schema::create('tours', function (Blueprint $table) {
          $table->increments('id');

          $table->string('name', 125);
          $table->string('slug')->index();
          $table->text('description')->nullable();
          $table->string('duration')->nullable();
          $table->string('url')->nullable();

          $table->boolean('ended')->default(false)->index();

          $table->timestamps();
        });
        DB::statement('ALTER TABLE tours ADD FULLTEXT search(name)');
    }

冒险模式的迁移与旅游相同。这两个模型之间不共享关系。

标签: laravellaravel-5

解决方案


我认为您正在寻找合并两个集合laravel.com/docs/5.8/collections#method-merge的 merge() 方法

        //Get all Tours
        $tours= Tour::orderBy('created_at', 'desc')->get();

        //Get all adventures
        $adventures= Adventure::orderBy('created_at', 'desc')->get();

        //Merge both collection into 1 single collection and group according the date
        $dates= $tours->merge($adventures)->groupBy(function($item) {
            return $item->created_at->format('d-M-y');
        });

        return view('someView', compact('dates'));

然后你可以在日期内循环

        @foreach($dates as $date => $activity)
            <h2>{{$date}}</h2>
            <li>
                {{$activity}}
            </li>
        @endforeach

推荐阅读