laravel - 如何在 Laravel 5.5 中创建按日期分组的两个模型的集合?
问题描述
我有两个模型Tour
和Adventure
. 我想做一组按日期分组的旅行和冒险。并像这样显示它:
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)');
}
冒险模式的迁移与旅游相同。这两个模型之间不共享关系。
解决方案
我认为您正在寻找合并两个集合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
推荐阅读
- c++ - 使用 DX11 加载 2D 纹理时的内存泄漏
- python - 如何在Python中查找用户名是否存在于文件中
- windows - 将命令输出保存到变量不起作用
- vue.js - Child-Parent-Communication:找不到方法?
- c - 如何找出为结构创建的数组中的元素数量?
- html - Rails 错误:自动播放有时仅适用于 video_tag
- php - 作为 AJAX 成功函数的一部分,从 API 调用发送 PHP 的 JSON 响应
- java - 我的套接字连接是否丢弃了通过它发送的一些数据?
- python - 删除列表中的字符串
- python - 当我运行我的 GB 模型时,我得到“TypeError:'CategoricalDtype' 类型的对象没有 len()”,这是什么意思,我该如何解决?