I have 3 tables: Account, User and Organization.
Account consists of id, name and organization_id.User consists of email and organization_id.Organization consists of id and name.Each Account is registered to an Organization(through organization_id) and each User is registered to an Organization. The challenge is to display all the emails (from User) to the Account corresponding to the name whose organization_id matches the organization_id of User.
Here's my code till now:
class Account(db.Model):
    __tablename__ = "account"
    id = Column(Integer, primary_key=True)
    name = Column(String(50), index=True, unique=True)
    organization = Column(Integer, 
        ForeignKey("organization.id"),nullable=False, index=True)
class User(UserMixin, db.Model, RBACUserMixin):
    __tablename__ = "user"
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(255), unique=True)
    organization = Column(Integer, ForeignKey("organization.id"), 
                      nullable=False, index=True)
class Organization(db.Model):
    __tablename__ = "organization"
    id = Column(Integer, primary_key=True)
    name = Column(String(512))
    users = relationship("User", backref="organizations")
    accounts = relationship("Account", backref="organizations")
                For this purpose, two tables are created in our SQLite database (college. db). The students table has the same structure as given in the previous section; whereas the addresses table has st_id column which is mapped to id column in students table using foreign key constraint.
The sqlalchemy backref is one of the type keywords and it passed as the separate argument parameters which has to be used in the ORM mapping objects. It mainly includes the event listener on the configuration attributes with both directions of the user datas through explicitly handling the database relationships.
Join user and account on organization id and filter based on name:
db.session.query(User.email).\
    join(Account, Account.organization == User.organization).\
    filter(Account.name == 'some name')
Query.join() allows passing arbitrary SQL expressions as the on-clause when using the 2 argument form.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With