这个Python3的答案完全是衍生的,它只是把上面的所有东西都放在一个小的自包含的MySQL工作示例中。我需要在表上实现多对多关系的唯一性约束。也许你可以运行这个来调试本地环境问题,在我的情况下,它们纯粹是在键盘和椅子之间:)
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Column, ForeignKey, Integer, String, UniqueConstraint
from sqlalchemy.orm import relationship
import logging
logging.basicConfig()
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://user:pass@localhost/mydb'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
user_role = db.Table(
'user_role',
Column('uid', String(6), ForeignKey('user.uid')),
Column('role', String(32), ForeignKey('role.name')),
UniqueConstraint('uid', 'role', name='idx_uid_role'))
class UserModel(db.Model):
__tablename__ = 'user'
uid = Column(String(6), primary_key=True)
create_time = Column(Integer, nullable=False)
login_time = Column(Integer, nullable=True)
roles = relationship('RoleModel', secondary='user_role',
backref='user', lazy='joined')
class RoleModel(db.Model):
__tablename__ = 'role'
name = Column(String(32), primary_key=True)
description = Column(String(256), nullable=False)
db.create_all()
运行此命令后,检查为表定义的索引,如下所示:
mysql> show index from user_role;
你应该看到:
+-----------+------------+--------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | Visible | Expression |
+-----------+------------+--------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
| user_role | 0 | idx_uid_role | 1 | uid | A | 0 | NULL | NULL | YES | BTREE | | | YES | NULL |
| user_role | 0 | idx_uid_role | 2 | role | A | 0 | NULL | NULL | YES | BTREE | | | YES | NULL |
| user_role | 1 | role | 1 | role | A | 0 | NULL | NULL | YES | BTREE | | | YES | NULL |
+-----------+------------+--------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
3 rows in set (0.00 sec)
创建测试数据:
mysql> insert into user values ('abc123', 1, 2);
mysql> insert into role values ('role1', 'Description');
mysql> insert into user_role (uid, role) values ('abc123', 'role1');
最后,通过运行最后一次插入第二次测试唯一性约束,你应该看到:
mysql> insert into user_role (uid, role) values ('abc123', 'role1');
ERROR 1062 (23000): Duplicate entry 'abc123-role1' for key 'user_role.idx_uid_role'