简体   繁体   English

同时插入多个外键

[英]Insert Multiple Foreign Keys Simultaneously

I have a form that gathers user input regarding a property they showed (a realtor showing to potential business leasees).我有一个表格可以收集用户关于他们展示的财产的输入(向潜在的商业租赁者展示的房地产经纪人)。

Upon submitting the form, I insert the data into three tables: Showing , Business , and Contact .提交表单后,我将数据插入到三个表中: ShowingBusinessContact This form allows for the creation of new Businesses and new Contacts , while also creating a new Showing record.此表单允许创建新Businesses和新Contacts ,同时还创建新的Showing记录。

I can insert the information into either my Business table and my Contacts table fine with an auto-incrementing primary key .我可以使用自动递增的primary key将信息插入到我的Business表和我的Contacts表中。

How do I insert the primary key from Contacts as a foreign key in Business when they are both submitted at the same time?当它们同时提交时,如何将Contactsprimary key作为foreign key插入Business

Should I have a values table which I select from for both the primary key and the foreign key ?我应该有一个值表,我可以从中选择primary keyforeign key吗? What are the best practices around this?这方面的最佳做法是什么?

Additionally, I would like the insert the primary keys from both Business and Contacts as foreign keys in my Showing table.此外,我希望将BusinessContactsprimary keys作为foreign keys插入我的Showing表中。 I currently have a BusinessID as foreign key within Contacts but maybe Contacts should stand alone so that I can Insert it first and then just select for the subsequent foreign keys ?我目前有一个BusinessID作为Contacts foreign key ,但也许Contacts应该独立,以便我可以先Insert它,然后只选择后续的foreign keys

Finally I should note that for a database I am using phpMyAdmin and inserting via SQL within a .php page.最后,我应该注意,对于数据库,我使用phpMyAdmin并通过 SQL 插入到.php页面中。

To retrieve the value assigned to an AUTO_INCREMENT column when a row is inserted, MySQL provides a last_insert_id() function.为了在插入行时检索分配给 AUTO_INCREMENT 列的值,MySQL 提供了last_insert_id()函数。

Immediately following a successful insert that assigned a value to an AUTO_INCREMENT column, in the same session, before any other SQL statements are issued, you can run a query:在为 AUTO_INCREMENT 列分配值的成功插入之后,在同一会话中,在发出任何其他 SQL 语句之前,您可以立即运行查询:

SELECT LAST_INSERT_ID()

The value returned from that can be used in a subsequent INSERT.从中返回的值可用于后续的 INSERT。 In your scenario, that value can be supplied as the value for the foreign key column.在您的方案中,该值可以作为外键列的值提供。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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