合并 Laravel 中的 5 个表并按 created_at 排序

Combine 5 tables in Laravel and sort by created_at

我正在制作广告网站,人们可以发布他们正在销售的东西。所以我有表:carstechnologyreal_estatepets 等。所有这些表都有不同的列,除了 "created_at" 列,这对所有表都是通用的。

示例:

CARS: [Model, Type, fuel type..., created_at]

PETS: [Name, Description..., created_at]

因此,如果 cars 有 5 行,pets 有 7 行,real_estate 有 3 行,我需要按 created_at 排序的 return 15 行。我需要合并所有 5 个(或更多)表并按 created_at 对它们进行排序(不丢失任何行)。 在 laravel (Eloquent) 中,您有一些技巧或想法吗?

我认为您无法对查询执行任何有用的操作。联合要求所有查询 return 相同数量的列,您可能不想连接这些表,因为那只会是一团糟。我相信最好的解决方案是使用 Collections.

$collection = new \Illuminate\Support\Collection();
$sortedCollection = $collection->merge($pets)->merge($cars)->merge($realEsate)->sortBy('created_at');