简体   繁体   中英

Query from multiple tables in supabase?

I have 2 tables in supabase. We have a post table and an image table. Each post contains multiple images. In my image table, I have the post_id and url . The post_id is a foreign key to post 's id.

Post Table:
| id       | contents       |
| -------- | -------------- |
| 1        | some content 1 |
| 2        | some content 2 |  

Image Table:
| id       | url                 | post_id|
| -------- | ------------------- | ------ |
| 10       | url2.com            | 1      |
| 11       | url1.com            | 2      |
| 12       | url3.com            | 2      |

I want my output to look like:

[
  {
    "id": 1,
    "content": "some content 1"
    "images": [
      "url2.com"
    ]
  },
  {
    "id": 2,
    "content": "some content 2"
    "images": [
      "url1.com",
      "url3.com"
    ]
  }
]

My fetch request looks something like this:

const fetchPosts = async (start, end) => {
    console.log(`Fetching all posts...`);

    return await supabase
    .getClient()
    .from('post')
    .select('*')
    .order('inserted_at', { ascending: false })
    .range(start, end);
}

and then I'm fetching images using each post id from that query. Is there away for me to just use one supabase query instead of looping through each post and fetching what images are linked to that post?

You can use JOIN queries using Supabase, eg:

const { data, error } = await supabase
  .from('image')
  .select(`
    id, url, post_id
    post (
      content
    )
  `)

Depending on their complexity, you can also encapsulate these calls in RPC functions .

For joins in multiple tables , then you can do the following:

const { data, error } = await supabase
  .from('products')
  .select(`
    id,
    supplier:supplier_id ( name ),
    purchaser:purchaser_id ( name )
  `)

It is important to set the Foreign key as part of your primary key as part of the way PostgREST v10 detects relationships .

Image Table Primary key should be:

alter table image drop constraint image_pkey, add primary key (id, post_id);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM