XataX
Xataโ€ข2y agoโ€ข
6 replies
maxfi

Reverse links typescript

Hi there. I'm wondering if it's possible to
read
a
ShoppingCart
by it's
id
and also get all it's
ShoppingCartLineItems
in one query. I'm trying to avoid making multiple queries to the database.

I've had a look at https://xata.io/blog/navigating-many-to-one and https://xata.io/docs/concepts/data-model#links-and-relationships but I'm still not sure how to do this.

Schema:

{
  "tables": [
    {
      "name": "ShoppingCarts",
      "columns": [
        {
          "name": "customerId",
          "type": "string"
        }
      ],
      "revLinks": [
        {
          "column": "shoppingCart",
          "table": "Users"
        },
        {
          "column": "shoppingCart",
          "table": "ShoppingCartLineItems"
        }
      ]
    },
    {
      "name": "ShoppingCartLineItems",
      "columns": [
        {
          "name": "shoppingCart",
          "type": "link",
          "link": {
            "table": "ShoppingCarts"
          }
        },
        {
          "name": "productId",
          "type": "string"
        },
        {
          "name": "quantity",
          "type": "int"
        },
        {
          "name": "type",
          "type": "string",
          "defaultValue": "product"
        }
      ]
    }
  ]
}


What seems to work is:

const record = await xata.db.ShoppingCarts.select([{
    name: "<-ShoppingCartLineItems.shoppingCart",
    columns: ["productId", "quantity", "type"],
    as: "lineItems"
}]).filter({ id: "rec_cno400v3e8os6tplq4jg"}).getFirstOrThrow()


However,
record
doesn't have a
lineItems
prop. ๐Ÿค”
Addressing the N+1 problem and navigating one-to-many relationships with Xata's new approach.
Reduce query round trips with improved one-to-many relations
A relational data model with schemaful flexibility and JSON support
Data model
Was this page helpful?