简体   繁体   中英

How to insert data in a table with foreign keys?

Good evening guys, I hope you all are well. I'm from latin america, so I hope you excuse my writing.

I have a database with 3 tables:

  1. tenant (the users)
  2. company (the user's companies)
  3. company_x_tenant (which is generated by the relation many-to-many that tenant and company have)

so company_x_tenant has foreign keys (that are the primary keys that company and tenant have).

I'm trying to insert data into company_x_tenant table, but it's not allowed until I insert data into the tenant table and then the company table.

The problem is that I don't know if when I insert data into the company table, I should make a second insert to the company_x_tenant table. My boss says that the company_x_table exists because the website needs to prevent every user from deleting any company, so just one user can have complete access to it's own companies and delete or update them.

I hope I made myself clear :( Thank you!!

If only one user should be related to a company in this manner, there is no need for the company_x_tenant table; those are mostly for "many to many" relationships. Just put some "owner_user_id" field in the company table that is a foreign key to users.user_id.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM