阿里巴巴开发手册强制不得使用外键和级联,一切外键概念必须在应用层解决
1. 外键
foreign key 一个表中的一个字段引用了另一个表中的键,引用的表叫做子表,被引用的表叫做主表,外键是一种约束,描述的是表之间的关系。
2. 级联
删除主表的记录同时删除子表的记录,或者更新主表的键同时更新相应子表的记录,这些都是级联操作。
很多orm框架都会自动开启外键的级联操作,但有些时候我们的业务并不需要这种级联操作,使用外键会变得麻烦。
外键和级联不适合分布式的系统
3. 应用层解决
使用联表查询替代外键关联查询
// 根据user表的查询条件进行子查询,然后左连接role表select u.*, role.*from (select * from user where `user`.username = 'cyj' limit 10) as uleft join role on u.id = `role`.user_id
程序内部处理联表查询的数据
type UserAndRole struct {*User*Role}func main() {// results是查询的结果,每条数据映射为UserAndRoleusers := make([]*User, 0, len(uMap))uMap := make(map[uint]*User)for index := range results {user := results[index].User// 利用map的key的特性进行去重value, ok := uMap[user.ID]if !ok {uMap[user.ID] = userusers = append(users, user)value = user}// 把角色放入到user的Rolesvalue.Roles = append(value.Roles, results[index].Role)}}
