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

查看:193
本文介绍了在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.

示例:

CARS:[型号,类型,燃料类型...,created_at]

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

PETS:[名称,说明...,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)?

推荐答案

我不认为您可以对查询执行任何有用的操作.并集要求所有查询返回相同数量的列,您可能不希望连接这些表,因为那样只会造成混乱.我相信最好的解决方案是使用Collection s.

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 \Illuminate\Support\Collection();
$sortedCollection = $collection->merge($pets)->merge($cars)->merge($realEsate)->sortBy('created_at');

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

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