jackade2024's avatar

Multiple tables that share the same structure

Hi,

I have a problem with multiple tables that share the same structure.

For example, I have several orders tables for each year, such as orders_2020, orders_2021, and so on. These tables are created dynamically every year.

Now, I want to handle all of them through a single model called OrderAll.

I would like to use this model in a way that allows me to access all Eloquent functionalities, such as OrderAll::query()->select()->whereHas()->whereJsonContains()->with(), etc.

Is there any way to implement this approach? I already tried extending Eloquent with custom Builder classes like UnionEloquentBuilder and UnionQueryBuilder, but it doesn’t work correctly with relationships and other functionalities. I keep running into bugs and unhandled errors.

use Illuminate\Database\Query\Builder; use Illuminate\Database\Eloquent\Builder; use Illuminate\Contracts\Pagination\LengthAwarePaginator;

I want this solution to work for both MySQL and PostgreSQL.

I would be very happy and grateful for your help.

Thanks a lot.

0 likes
6 replies
JussiMannisto's avatar

You should not have separate tables for every year. That is not how relational databases should be designed. I would make it my first priority to migrate the tables into a single orders table.

When you dynamically create tables like that, you can't use foreign key relations referencing those tables without also creating separate versions of every related table. It would be a complete mess, and you can't query the data efficiently.

1 like
martinbean's avatar

@jackade2024 Well I mean, if you randomly decide to split your data into multiple tables like this then yes, you’re going to have multiple tables share the same structure.

Why have you done this in the first place? Database tables are capable of handling millions and millions of rows. You don’t need to split data by year. At all.

Glukinho's avatar

My guess is database structure comes from external system and can't be changed.

Something like annual export from old legacy system without any customization available.

Tray2's avatar

That shouldn't be a problem, it's easy to convert into a single orders table that fits the need.

Please or to participate in this conversation.