简体   繁体   中英

Relationship across a many-to-many table

I want to create a relationship across a many-to-many table, a User has Roles which have a Project . I want a relationship in the User to all Projects related to its Roles . I tried much with primaryjoin and secondaryjoin but i don't get it working.

Here are my models:

roles_users = db.Table('roles_users',
  db.Column('role_id', db.Integer, db.ForeignKey('role.id')),
  db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
  db.PrimaryKeyConstraint('role_id', 'user_id')
)

class User(db.Model, UserMixin):
  id = db.Column(db.Integer, primary_key=True)
  username = db.Column(db.Unicode(80), unique=True, nullable=False)
  roles = db.relationship('Role', secondary=roles_users, backref='users')
  projects = db.relationship('Project' ???? )

class Role(db.Model):
  id = db.Column(db.Integer, primary_key=True)
  name = db.Column(db.Unicode(80), unique=True, nullable=False)
  project_id = db.Column(db.Integer, db.ForeignKey('project.id'), nullable=False)

class Project(db.Model):
  id = db.Column(db.Integer, primary_key=True)
  name = db.Column(db.Unicode(80), nullable=False)
  roles = db.relationship('Role', backref='project')

The problem is in your "references". I refer you the following links that will help you to understand the constraints and relationship.

http://docs.sqlalchemy.org/en/rel_0_9/orm/relationships.html#many-to-many

This is the link which I found best for association.

http://docs.sqlalchemy.org/en/rel_0_9/orm/relationships.html#association-object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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