6

How can I query a one-to-one relationship with foreign key in supabase?

My tables:

  1. games (id, created_at, played_at)
  2. results (game_id, key)

Data: games

("id": 1, "created_at": "2022-03-02T11:01:11+00:00", "played_at": "2022-04-02T12:15:06+00:00")

Data: results

("game_id": 1, "key": "alyktm3cf11bypgg")

My supabase query looks like this:

    const { data, error } = await supabase
        .from('games')
        .select('*, registrations(walletKey), results(key)')
        .order('scheduled_at')
    ;

The result contains an array of registrations, like here:

{
    "id": 1,
    "created_at": "2022-03-02T11:01:11+00:00",
    "played_at": "2022-04-02T12:15:06+00:00",
    "results": [
        {
            "key": "alyktm3cf11bypgg"
        }
    ]
}

But since there will always only be one result, can I modify my query to get this?

{
    "id": 1,
    "created_at": "2022-03-02T11:01:11+00:00",
    "played_at": "2022-04-02T12:15:06+00:00",
    "results": 
    {
        "key": "alyktm3cf11bypgg"
    }

}

Or even this:

{
    "id": 1,
    "created_at": "2022-03-02T11:01:11+00:00",
    "played_at": "2022-04-02T12:15:06+00:00",
    "key": "alyktm3cf11bypgg"
}
1
  • If it's okay to convert post-facto (using vanilla JS), then may be give this a try: const newDataObj = Object.fromEntries(Object.entries(oldDataObj).map(([k, v]) => (k !== 'results' ? [k, v] : ["key", v?.[0]?.key])));. I assume the objective is not this - but rather get the result from directly in the format.
    – jsN00b
    Apr 3, 2022 at 13:35

1 Answer 1

0

This can be achieved by using the single() method:

const { data, error } = await supabase
    .from('games')
    .select('*, registrations(walletKey), results(key)')
    .order('scheduled_at')
    .single();

Note, that if the query does NOT return a single row, the method will return an error (i.e. the data field will be undefined or null while the error field will be defined).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.