Comment

Comment by saila

You could probably get this down to two queries, one for posts and one for comments, if you aggregate the vote count when retrieving the comments. I think this is pretty easy to do with most ORMs.

You could also get it down to 1 query using SQL. This is one way to do it based on the schema in the article [postgres, not well tested]:

    with
      latest_posts as (
        select * from post limit 3
      ),
      latest_comments as (
        select
          c.*, count(v.id) as votes
        from
          comment c
        left join
          vote v on v.comment_id = c.id
        where
          c.post_id in (select id from latest_posts)
        group by
          c.id, c.content
      )
    select
      p.*, json_agg(c)
    from
      latest_posts p
    left join
      latest_comments c on c.post_id = p.id
    group by
      p.id, p.title, p.content

    # NOTE: fixed SQL bug noted by @rurabe
Off the top of my head, I'm not sure how you would (or if you could) do this with ActiveRecord, SQLAlchemy, or the Django ORM, but it's probably more complicated than just writing the SQL.

To be clear, I'm not anti-ORM and use them all the time, but it really helps to understand SQL well when using them and to know when it's appropriate to switch to SQL.

parent saila 3 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton