A
A
Anton2016-08-23 05:43:43
Ruby on Rails
Anton, 2016-08-23 05:43:43

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

2 answer(s)
R
riot26, 2016-08-23
@hummingbird

Table structure:

blogs (`id`, `title`);
posts (`id`, `blog_id`, `title`);
comments (`id`, `post_id`, `text`);

Request:
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`

Result:
| 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      |

sqlfiddle
details

A
Artem Pyankov, 2016-08-23
@ibub1ik

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 question

Ask a Question

731 491 924 answers to any question