Search code examples
mysqllaravelgreatest-n-per-groupquery-performance

Optimal database schema structure


I am building a forum web application on Laravel.

While users are on topics page, every topic will be shown with additional relation datas, such as number of posts in the topic, last post even the author of the last post of the topic.

Given the fact that there will be deeply nested relational datas with every topic, is it okay to access these properties via relationships or I should store these datas in separate columns of the topics table in order to achieve normal performance?

I know it would be better to store the datas directly in the parent table, but MUST I? What is a best practice in terms of performance and normalization?


Solution

  • The best practice in terms normalization would be to get all data via relationships.

    In terms of performance, you should be caching anything that is costly to compute.

    I'd write a scheduled job that updates the cache with fresh data for all topics every few minutes.

    Here's more information on Laravel's caching and task scheduling.