Sorting the 2nd (child) table by order when it's joined by a Foreign Key relation in Supabase

246 Views Asked by At

Using next.js with Supabase, is it possible to sort on an 'order by' statement for a table which is a child of another (joined by Foreign Key relation)?

For example: User's profile data on stored on the Profile table. the each user can add products to the products table, therefore want to query the database and return the user's profile data (to show at the top of the page), then output a list the products for that specific to that user. The final part (which I can't get working) is sorting the order of the products.

Here is my query code in next.js:

useEffect(() => {
  let query = supabase.from('profile').select('*, product(product_id, title, price, created_at)');
  query = query.order('product.product_id', { ascending: false });

  const fetchData = async () => {
    const { data, error } = await query;
    setData(data || []);
  };

fetchData();
}, []);

This returns the following error:

'unexpected "p" expecting "asc", "desc", "nullsfirst" or "nullslast"', hint: null, message: '"failed to parse order (product.product_id.asc)

So failing on calling the product.product_id. i've also tried product.price etc. to no avail.

Interestingly using Superbase's SQL Editor where I can get the desired result running this SQL:

select *
from profile
join product on profile.id = product.profile_id
order by
product.product_id asc

I'm aware one solution might be is to sort the data with JavaScript once the database has responded, however I first wanted to see if it could be handled by the database.

I should also note i'm using next.js version 13 with and importing Supabase like this:

import { createClientComponentClient } from '@supabase/auth-helpers-nextjs'

and initialising like this:

const supabase = createClientComponentClient()
0

There are 0 best solutions below