https://supabase.com/ logo
Hello... trying to reference the auth users table ...
# javascript
l
Hello... trying to reference the auth users table via a field called 'owner' in the query below..
Copy code
js
const { data, error } = await supabase
  .from('Comments')
  .select(`id, owner:users(id,email)`)
  .eq('post_id', params.id);
I keep receiving an error
Could not find a relationship between 'Comments' and 'users' in the schema cache
I'm not really sure why as it appears I've setup the foreign key correctly. Any suggestions are appreciated
users is from auth
g
You can not access the auth schema from the API. You need to copy to a public profile/users table as suggested in the docs, or use an rpc call with a security definer function to get to the auth.users table.
l
thanks for the link!
the trigger seems vulnerable to mistakes lol.. do you have one that you use for this more robust than the docs?
doesn't the function need to check if the user id already exists?
Copy code
-- trigger the function every time a user is created
create trigger on_auth_user_created
  after insert on auth.users
  for each row 
  when (old.id is distinct from new.id)
  execute procedure public.handle_new_user();
g
If you are using auth to create a new user and it inserts a user row into auth how would the user exist in your public table? If you want to deal with updates to auth.users, you need a 2nd function on update trigger, or you can have one trigger function look at the op (update, insert) and decide what to do.
l
valid point!
g
This is the sum of my insert user trigger function (I don't deal with updates of email yet, and don't use user_metadata)
Copy code
create function handle_new_user() returns trigger
    security definer
    language plpgsql
as
$$
begin
  insert into public.users (uid, email)
  values (new.id, new.email);
  return new;
end;
$$;
I recommend not to use public.users as the table, public.profiles is a better choice. I regret picking users....
l
ha thanks.. i almost did go with users
g
It just causes confusion with the same name as auth.users in code.
l
yeah for sure, i can see that happening
how did you check to see what values the "new" object has when setting up this trigger? Feels like a lot of trial and error.. i guess i could disable it and login client side to check the user object
g
new has all columns of the table the trigger is on.
l
ohh so auth.users ... hmmm don't see avatar url
oh wait i don't need that in this case