简体   繁体   English

在PHP MySQL中处理多对多关系的最佳方法

[英]Best way to handle Many-to-Many relationships in PHP MySQL

I am looking for the best way to handle a database of many-to-many relationships in PHP and MySQL. 我正在寻找处理PHP和MySQL中多对多关系数据库的最佳方法。

Right now I have 2 tables: 现在我有2个表:

Users (id, user_name, first_name, last_name) 用户(id,user_name,first_name,last_name)
Connections (id_1, id_2) 连接(id_1,id_2)

In the User table id is auto incremented on add and user_name is unique, but can be changed. User表中, id在add上自动递增, user_name是唯一的,但可以更改。 Unfortunately, I don't have control over the user_name and its ability to be changed, but I must account for it. 不幸的是,我无法控制user_name及其更改的能力,但我必须考虑到它。

The Connections table is obviously, user1 and user2's id. Connections表显然是user1和user2的id。

The connection table needs to account for these possible relations: 连接表需要考虑这些可能的关系:

user1 --> user2 (user 1 friends with user 2 but not user2 friends with user1) 
user2 --> user1 (user 2 friends with user 1 but not user1 friends with user2) 
user1 <--> user2 (user 1 and user 2 mutually friends) 
user1 <-!-> user2 (user 1 and user 2 not friends) 

That part is not the problem, The problem I am having with is keeping these relations unique when and if they change in batches. 那部分不是问题,我遇到的问题是当这些关系分批改变时保持这些关系的独特性。

Possible solution 1: delete all of user 1's relations and readd them with the updated list. 可能的解决方案1:删除所有用户1的关系并使用更新的列表读取它们。 I think this might be too slow for my needs. 我认为这可能对我的需求来说太慢了。

Solution 2? 解决方案2? Anyone else encounter this problem? 其他人遇到这个问题? How should I best handle this? 我应该如何最好地处理这个?

update: distinguishing relationships: 更新:区分关系:

i handle relationships like this: 我处理这样的关系:

user1, user2
user1, user3
user2, user1

in that example the following is true: 在该示例中,以下情况属实:
user1 follows user2 and user3 user1跟随user2和user3
user2 only follows user1 but doesn't follow user3 user2仅跟随user1但不跟随user3
user3 doesn't follow either user1 or user2 user3不遵循user1或user2

如果您遇到唯一性问题,可以使用两个列(id_1,id_2)在Connections上使用复合主键。

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

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