Reputation: 40428
How can I query a one-to-one relationship with foreign key in supabase?
My tables:
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"
}
Upvotes: 6
Views: 3603
Reputation: 569
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).
Upvotes: 0