Ad

Combine 5 Tables In Laravel And Sort By Created_at

- 1 answer

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

Ad

Answer

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');
Ad
source: stackoverflow.com
Ad