如何在普通PHP中同步pivot表
假设我们有这些桌子如何在普通PHP中同步pivot表,php,mysql,sql,pivot,Php,Mysql,Sql,Pivot,假设我们有这些桌子 Users table ----------- id name ----------- 1 xxx 2 yyy 3 ccc 4 bbb 5 aaa Location table ------------- id name ------------- 6 Spain 7 Russia 8 Germany 9 USA Pivot table ------------------------ id user_id location_i
Users table
-----------
id name
-----------
1 xxx
2 yyy
3 ccc
4 bbb
5 aaa
Location table
-------------
id name
-------------
6 Spain
7 Russia
8 Germany
9 USA
Pivot table
------------------------
id user_id location_id
------------------------
1 1 6
2 2 8
3 1 8
4 1 9
5 3 8
我想要实现的是同步数据透视表中的数据。
因此,我有一个post请求,其中包含用户id=[1,5,4]数组和位置id=8。所以我会得到下面的结果
[updated] Pivot table
-------------------------
id user_id location_id
-------------------------
1 1 6 <-- This one stays
3 1 8
4 1 9
6 5 8 <-- Added
7 4 8 <-- Added
...we deleted the row with location_id=8 and user_id=2 and user=3 because those are not in the users array
[更新]透视表
-------------------------
id用户\u id位置\u id
-------------------------
1 1 6不确定这是否是最好的方法(实际上删除所有内容,然后插入值似乎更容易、更清晰),但如果出于某种原因您希望保留透视表ID,这里有一种方法:
考虑两个透视字段(用户id、位置id),为表定义唯一索引
使用user\u id=user\u id和location\u id=location\u id插入所有数据,这样,如果有重复的值,mysql将保留它们而不进行修改,并且不会抛出错误
从请求中内爆数组ID并从表中执行删除,其中数据不在指定的值中