Sniffer
Sniffer

Reputation: 6412

Superbase db query from URL

I'm struggling to formulate a supabase db query from multiple tables, whilst using a value from a URL.

I have 3 tables (simplified)...

series > id, series
authors > id, name
books > id, title, series_id(fk), authors_id(fk)

I want to get a list of books in a series, along with the author and series name from the following URL...

app.com/series. i.e. app.com/harrypotter

I can get the series name using getServerSideProps, but struggling how to write my query to supabase. Every way I write it either gives me a NULL object or a 500 error.

I feel like I should be querying the books table and then be able to get the series and author names through the foreign keys. But the query that it's centred around is the series name, which is in the series table. So unsure of the db query to do it, or whether I should structure my db table's in a different way?

  export async function getServerSideProps( context ) {
      const { series } = context.query;
        ...
      return {
        props: {
        ...
        }
      };
    }

Thanks for any help in advance!

Upvotes: 1

Views: 559

Answers (1)

Sean W
Sean W

Reputation: 6608

Please ensure you have foreign keys set up, and then you can use Supabase to query foreign table examples (SQL join).

There needs to be more data to give an exact answer, but here are the relevant docs.

I also included logs and a try/catch so you can see your exact errors and where your code is failing.

const Page = (props) => {
 console.log(props)// logged to browser's console
 return <>Your page<>;
}


export async function getServerSideProps( context ) {
 try {
  const { series } = context.query;
  console.log("series", series); // ensure series is present and check if is an object
  const { data, error } = await supabase.from('series')
  .select(`
    id,
    title,
    book (
      title // you can also use `*` check out select all docs
      author (
       name
      )
    )   
  `)
   .eq('id', series)
   .limit(1)
  
  
  console.log("error", error);
  console.log("data", data);

  return {
   props: {
    series: data
   }
  }
 } catch (e) {
  console.log(e);
 }
}
export default Page;

Note: getServerSideProps logs will show up in your server's console (where you run npm dev) - not the browser's console. You should remove the console logs once you figure out what's happening.

Upvotes: 4

Related Questions