R
R
runprogr2019-12-08 16:44:37
Laravel
runprogr, 2019-12-08 16:44:37

How to link a post to a topic?

I’m just starting my journey in Laravel, so I decided to make a simple forum for testing.
There is a topic entity with a hasMany Post relationship
There is a post entity with a belongsTo Topic relationship
When we create a Topic, we immediately create a post that will be the starting one. And which will always be the first in the topic and which cannot be deleted.
So far, I have found only two options -
1) register the post_id column in the topic model, which will contain the number of the linked post. Then it will be necessary to make two queries to the database, pull out the Topic and the linked Post, and then another query for all other posts. But here the problem with pagination appears, because the first post is not counted and there will be one more posts on the first page than on the rest
2) In the Post model, add the column main, in which to put down 0 or 1. And first, we sort through the array with the condition to display only posts where main==1, and then we sort through the array again with the condition main=0.
Not sure if any of these options are correct. How to do it better ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Daria Motorina, 2019-12-08
@runprogr

The first option doesn't work.
The second case - it's not entirely clear why you need two forechs - you want to display the first posts when displaying the list of topics (as I understand it), the second time display all the posts associated with the topic, but here main 1 | 0 no longer plays a role. Those. for one task, you need to pull posts once, just according to different criteria.
The main post for a topic can be determined by the date of creation (the first one when sorted by date) and cached (so as not to waste resources searching for the first post each time), so as not to use additional. flag column.
At the level of business logic (php code), it is necessary to prohibit deleting the first post.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question