[英]PHP implementation of n:m relationship
As to implement a N:M relationship of tables USERS
(PK: user_id which is auto increment INT) and REQUESTS
(PK: request_id which is auto increment INT), I've created the intermediate table USERS_GROUPS
(PKs: two FKs US_userid, US_requestid which coincide with the PKs of USERS
and REQUESTS
). 为了实现表
USERS
(PK:自动递增INT的user_id)和REQUESTS
(PK:自动递增INT的request_id)的N:M关系,我创建了中间表USERS_GROUPS
(PK:两个FK US_userid,US_requestid与USERS
和REQUESTS
的PK一致。 When a user creates a new request I have to create a new record inside REQUESTS
. 当用户创建新请求时,我必须在
REQUESTS
内创建新记录。
INSERT INTO REQUESTS (...) VALUES (...);
At the same time I want to create a new record inside USERS_GROUPS
as to join USERS_GROUPS
with USERS
and REQUESTS
. 同时我想创建一个内部的新纪录
USERS_GROUPS
作为加入USERS_GROUPS
与USERS
和REQUESTS
。 The value of the first FK pointed to USERS
is known to me, however how may I find the value of the second FK pointed to the record I've just created? 指向
USERS
的第一个FK的值对我来说是已知的,但是如何找到指向刚刚创建的记录的第二个FK的值呢?
In other words, I want to find the value of the field request_id of the record I've just created. 换句话说,我想找到我刚刚创建的记录的字段request_id的值。 This seems a little bit confusing to me and I don't know how to implement it.
这对我来说似乎有些混乱,我也不知道如何实现。
INSERT INTO USERS_GROUPS (US_userid,US_request_id) VALUES (...,?????);
This is my first serious db schema I've ever created and my first n:m relationship I have to manage. 这是我创建的第一个严肃的数据库模式,也是我必须管理的第一个n:m关系。 Is my point of view correct?
我的观点正确吗? If yes, I 'd appreciate your help in how to realise it.
如果是的话,非常感谢您的帮助。 If not which is the right approach?
如果不是,哪种方法正确?
You can use last-insert-id to retrieve the newly created id. 您可以使用last-insert-id检索新创建的ID。
The library you use to connect to database usually has a function for it, such as mysqli_insert_id or PDO::lastInsertId . 用于连接数据库的库通常具有一个函数,例如mysqli_insert_id或PDO :: lastInsertId 。
Sidenote: Because you are performing multiple (independent) queries on the database it may be necessary to wrap it all in transaction. 旁注:由于您正在数据库上执行多个(独立)查询,因此可能有必要将其全部包装在事务中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.