Enter data into a foreign key table

Asked

Viewed 614 times

4

I am trying to register a user put in his table there is a foreign key linked to another table.

My problem is that this foreign key is referencing the address table, only I still have no address for this user, I want it to be able to register later when you want.

What can I be doing at the time of registration ? I have tried to leave the default value as null and 0 but it didn’t work out so well.

2 answers

2

Pedro, this is happening because your Foreign key by default is set to NOT NULL.

What you should do is change the Foreign key column to accept NULL. As I have no knowledge of your table, it would look something like this.

ALTER TABLE usuario MODIFY endereco_id INT NULL;

I’m not sure why I’m not with the Mysql environment here, but you might have to drop the contraint from your Foreign key, modify it to accept NULL and then add the Constraint again.

1


Your bank has the need to have such a relationship?

You see, the right thing would be for you to have a Users relationship to Addresses 1:N, namely a User may have more than one Address.

inserir a descrição da imagem aqui

That way you wouldn’t need to enter an Address Id in the Users.

But if this should be the way you are creating then I suppose you have an address table already registered in your bank (Post Office Base) for example, even so it would be a relationship bad, would not have the street number or as it informs another address if necessary.

If you really need to create your bank the way you are talking then don’t use the Address ID defined as not null.

  • Perfect guy, THANK YOU SO MUCH ! just this logic I needed. Thank you !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.