在 Laravel 中合并 5 个表并按 created_at 排序 [英] Combine 5 tables in Laravel and sort by created_at

查看:49
本文介绍了在 Laravel 中合并 5 个表并按 created_at 排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm making website for advertisements and people can publish things they are selling. So I have tables: cars, technology, real_estate, pets etc. All these tables have different columns except "created_at" column which is common for all tables.

示例:

汽车:[型号、类型、燃料类型...,created_at]

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

宠物:[名称,描述...,created_at]

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

因此,如果 cars 有 5 行,pets 有 7 行,real_estate 有 3 行,我需要返回 15 行,按 created_at 排序.我需要合并所有 5 个(或更多)表并按 created_at 对它们进行排序(不丢失任何行).你有一些技巧或想法如何在 laravel (Eloquent) 中做到这一点?

So if cars has 5 rows and pets has 7 and real_estate has 3 I need in return 15 rows sorted by created_at. I need to merge all 5 (or more) tables and sort them by created_at (without losing any of rows). Do you have some tips or idea how to do that in laravel (Eloquent)?

推荐答案

我不相信您可以对查询做任何有用的事情.联合要求所有查询返回相同数量的列,您可能不想加入这些表,因为那只会造成混乱.我相信最好的解决方案是使用 Collections.

I don't believe there would be any useful things you can do to the query. Unions require all queries to return the same amount of columns, you probably don't want to join these tables because that would just be a confused mess. I believe the best solution would be to use Collections.

$collection = new IlluminateSupportCollection();
$sortedCollection = $collection->merge($pets)->merge($cars)->merge($realEsate)->sortBy('created_at');

这篇关于在 Laravel 中合并 5 个表并按 created_at 排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆