Combine 5 tables in Laravel and sort by created_at

北慕城南 提交于 2019-12-04 06:03:00

问题


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.

Example:

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

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

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)?


回答1:


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');


来源:https://stackoverflow.com/questions/34858480/combine-5-tables-in-laravel-and-sort-by-created-at

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!