A
A
Alexey Sklyarov2020-10-15 21:54:02
Laravel
Alexey Sklyarov, 2020-10-15 21:54:02

How to correctly implement two different types of post with different add. fields?

I am writing a project in which there are only two categories (they can also be just one of the types of posts). There are two different sets of additional fields for posts in these categories. The question arises, how to implement it correctly?

There are two options that immediately come to mind:
1. Create a standard Post model, which will contain data for posts of both categories, and a table, for example, post_meta, in which I would indicate: post_id, meta_name, meta_value (as is done in Wordpress ).
2. Create a Post interface, create two models for posts of each category, and define sets of custom fields for these models, which will be the corresponding fields of the database table. I don’t like this option because of the lack of extensibility, that is, if I need to create (not a fact, but everything happens), a third type of post, with its own custom fields, then I will have to create a separate model again. The same problem will occur when adding new custom fields to existing models, since you will have to add these fields as table columns in the database.

How is this implemented in normal projects? Only the algorithm is of interest.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex Wells, 2020-10-16
@Alex_Wells

One common table with posts and their IDs
An additional table with additional fields for specific cases that you will join (of course, in a normal way, you need some kind of package for this, relays are out of place).
Fields in the additional table can have the post id as the primary key without problems, they don't need their own id.
json meta field is also an option, but slower. If selections and relationships are not needed or not particularly needed, then this is generally a great option.
A separate meta_name and meta_value table is generally the worst of the worst options. Neither the advantages of separate tables, nor any profit over a regular json field (because if you really need selections, then separate tables give you types, normal indexing, normal constraints, foreign values, etc., and if you don’t need it, then json is stupidly simpler than a separate tables). Choose from the two options above.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question