2017-10-25 3 views
0

Ich habe 4 Tabellen, Vendor, Products und ProductGroupings und eine Join-Tabelle namens Products_ProductGroupings. Ich versuche, alle ProductGroupings Verbindung mit Products auf Products_ProductGroupings wo Products.vendor == <A Vendor Instance>.Wie macht man einen Join mit einer Join-Tabelle?

Was ich nicht tun kann, ist die richtige Syntax für die Join-Tabelle zu finden.

Alternativ kann, da ProductGroupings hat eine Eigenschaft namens products Ich möchte products alle ProductGroupings deren abfragen vendor<A Vendor Instance> haben.

class Products(db.Model): 
    __tablename__ = 'products' 

    id = db.Column(db.Integer, primary_key=True) 
    parent_id = db.Column(db.Integer, db.ForeignKey('products.id')) 
    parent = db.relationship('Products', backref='children', remote_side=[id]) 
    groupings = db.relationship('ProductGroupings', secondary=Products_ProductGroupings, backref='products') 


class ProductGroupings(db.Model): 
    __tablename__ = 'product_groupings' 

    id = db.Column(db.Integer, primary_key=True) 
    date_created = db.Column(db.DateTime(timezone=True), nullable=False, default=datetime.datetime.now) 


Products_ProductGroupings = db.Table(
    'products_product_groupings', 
    db.Column('product_id', db.Integer, db.ForeignKey('products.id')), 
    db.Column('product_grouping_id', db.Integer, db.ForeignKey('product_groupings.id')) 
) 

class Vendors(db.Model): 
    __tablename__ = 'vendors' 

    id = db.Column(db.Integer, primary_key=True) 
    hash = db.Column(db.Text(10), nullable=False, default=create_hash) 
    vendor_id = db.Column(db.Integer, db.ForeignKey(Vendors.id), nullable=False) 
    vendor = db.relationship(Vendors, backref='products', foreign_keys=[vendor_id]) 
+0

Post (relevante Teile) Ihrer Modelle. –

+0

@ IljaEverilä Hinzugefügt Modelle. – ruipacheco

+0

Ich glaube, Sie haben die Beziehung/Fremdschlüssel zwischen Produkten und Lieferanten –

Antwort

1

Sie können einfach entlang der ORM Beziehung verbinden:

db.session.query(ProductGroupings).\ 
    join(Products, ProductGroupings.products).\ 
    filter(Products.vendor == v) 

Beachten Sie, dass die viele zu viele Beziehungen enden kann:

db.session.query(ProductGroupings).\ 
    join(ProductGroupings.products).\ 
    filter(Products.vendor == v) 

Alternativ Query.join() ein Punkt als zweites Argument beitreten akzeptiert Erstellen von mehreren Zeilen für eine einzelne ProductGroupings Einheit, aber dies ist nicht sichtbar, wenn nur eine einzige Entität abgefragt wird. Sie könnten auch filter on EXISTS:

db.session.query(ProductGroupings).\ 
    filter(ProductGroupings.products.any(Products.vendor == v)) 
Verwandte Themen