DEV Community

Cover image for STRAPI - Fetching data belongs to a model through another relationship (Graph database)
Aastha Talwaria
Aastha Talwaria

Posted on

6 1

STRAPI - Fetching data belongs to a model through another relationship (Graph database)

Suppose we have the following in schema:

  • country
  • homepage
  • topics
  • sources
  • sections
  • articles

And this is how they are related

ER diagram

  • homepage has one country.
  • homepage has many topics.
  • homepage has many sources.
  • topics belongs to many sections.
  • sources belongs to many sections.
  • sections belongs to many articles.

Requirement:
Get top 10 the articles for homepage having country id as countryId sorted by attribute_name.

My Approach:

async function findTopArticleByCountryId({ countryId, sortBy = 'likeCount' }) {
  try {
    const response = await strapi.connections.default.raw(
      `SELECT * FROM articles WHERE section IN (
        SELECT id FROM sections WHERE 
        topic IN (
          SELECT id FROM topics WHERE homepage IN (
            SELECT id FROM homepage WHERE country = ${countryId}
          )
        )
        OR service IN (
          SELECT id FROM sources WHERE homepage IN (
            SELECT id FROM homepage WHERE country = ${countryId}
          )
        )
      ) ORDER BY ${sortBy} DESC LIMIT 10;`
    );
    const [articles] = response;
//sanitize articles entity
    return articles;
  } catch (e) {
    console.log(e);
    return false;
  }
}
Enter fullscreen mode Exit fullscreen mode

Let's discuss your approach in the discussion box or you can hit me up at aastha.talwaria29@gmail.com.

Thanks for reading.

What if your devs could deploy infrastructure like launching a game?

What if your devs could deploy infrastructure like launching a game?

In this session, we'll show how you can build a user-friendly self-service portal for deploying infrastructure with Spacelift, in the flavor of deploying Minecraft servers.

Learn More

Top comments (0)

Gen AI apps are built with MongoDB Atlas

Gen AI apps are built with MongoDB Atlas

MongoDB Atlas is the developer-friendly database for building, scaling, and running gen AI & LLM apps—no separate vector DB needed. Enjoy native vector search, 115+ regions, and flexible document modeling. Build AI faster, all in one place.

Start Free

👋 Kindness is contagious

Explore this insightful write-up, celebrated by our thriving DEV Community. Developers everywhere are invited to contribute and elevate our shared expertise.

A simple "thank you" can brighten someone’s day—leave your appreciation in the comments!

On DEV, knowledge-sharing fuels our progress and strengthens our community ties. Found this useful? A quick thank you to the author makes all the difference.

Okay