我试图用连接表定义多对多关系,但我无法使用sqlalchemy来完成它。这是我定义的模型的一个例子:
class Bar(Model):
__tablename__ = 'bar'
bar_id = Column(BigInteger, primary_key=True)
class Foo(Model):
__tablename__ = 'foo'
foo_id = Column(BigInteger, primary_key=True)
owner_id = Column(BigInteger, nullable=False, index=True)
class FooBar(Model):
__tablename__ = 'foo_bar'
foo_id = Column(ForeignKey('foo.foo_id'), nullable=False, primary_key=True)
bar_id = Column(ForeignKey('bar.bar_id'), nullable=False, primary_key=True)
amount = Column(Integer)
foo = relationship('Foo')
bar = relationship('Bar')
class EnhancedBar(Model):
__tablename__ = 'enhanced_bar'
bar_id = Column(ForeignKey('bar.bar_id'), primary_key=True, nullable=False)
owner_id = Column(BigInteger, primary_key=True, nullable=False, index=True)
bar = relationship('Bar', backref=backref('enhanced_bar', uselist=False))
foos = relationship(
'Foo', secondary='foo_bar',
primaryjoin="and_(EnhancedBar.bar_id==FooBar.bar_id,"
"Foo.owner_id==EnhancedBar.owner_id)",
backref=backref('enchanced_bars',
primaryjoin="and_(EnhancedBar.bar_id==FooBar.bar_id, "
"Foo.owner_id==EnhancedBar.owner_id)")
)
EnhancedBar.foos关系及其backref当前工作正常,但我不确定这是否正确,因为以上是发出此查询:
SELECT * FROM foo, foo_bar WHERE :param_1 = foo_bar.bar_id AND foo.ownwer_id = :param_2 AND foo.foo_id = foo_bar.foo_id
实际上,我尝试发出以下查询:
SELECT *
FROM foo JOIN foo_bar ON foo.foo_id = foo_bar.foo_id
WHERE foo.owner_id = :owner_id_param AND foo_bar.bar_id = :bar_id_param
但我无法找到如何将其转换为sqlalchemy语言。是否有任何具体的符号我应该用来实现这个目标?