Answer the question
In order to leave comments, you need to log in
Is such a connection true?
There are three tables: blogs, posts and comments.
Now the links for them look like this:
blogs -> 1:n -> posts
posts -> 1:n -> comments
But I want to get a list of all related post comments on the blog page, so this link is:
blogs -> 1:n -> comments
The blog_id field is added to the comments table.
Is this the correct option? According to the rules of normalization - no. But how then to implement it?
Answer the question
In order to leave comments, you need to log in
Table structure:
blogs (`id`, `title`);
posts (`id`, `blog_id`, `title`);
comments (`id`, `post_id`, `text`);
SELECT
`comments`.*,
`blogs`.`id` as blog_id,
`blogs`.`title` as blog_title
FROM `comments`
JOIN `posts` ON `posts`.`id`=`comments`.`post_id`
JOIN `blogs` ON `blogs`.`id`=`posts`.`blog_id`
| id | post_id | text | blog_id | blog_title |
|----|---------|-------------|---------|------------|
| 1 | 1 | comment | 1 | Vasya |
| 2 | 2 | comment2 | 1 | Vasya |
| 5 | 2 | lorem ipsum | 1 | Vasya |
| 3 | 6 | comment3 | 2 | Petya |
| 4 | 10 | comment4 | 3 | Masha |
How it will look like in SQL has already been explained to you, in rails it is already out of the box:
class Blog < ActiveRecrod::Base
has_many :posts
has_many :comments, through: :posts
end
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question