[英]MYSQL query of one table that is a many to many relationship to another table
[英]syntax to query another table using relationship in ORM?
該模型是這樣的(在SQLAlchemy中):
Class Cell(Base):
__tablename__ = "cell"
id = Column(Integer)
name = Column(String)
Class Sample(Base):
__tablename__ = "cell"
id = Column(Integer)
factor_id = Column(Integer, ForeignKey("cell.id"))
cell = relationship(Cell, backref = 'sample', order_by = "Cell.id")
當我執行這樣的查詢時:
DBSession.query(Sample).filter(Sample.cell.name == "a_string")
它將引發如下異常:
File "build/bdist.linux-x86_64/egg/sqlalchemy/orm/attributes.py", line 139, in __getattr__
key)
AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object has an attribute 'name'
似乎Sample
類中的cell
字段沒有名為name
的字段。 然后,如何在帶有cell
字段的Sample
類中查詢Cell.name
? 有人對此有想法嗎?
謝謝!
有多種方法可以實現:
qry = session.query(Sample).join(Cell).filter(Cell.name == "a_string")
>> SELECT sample.id AS sample_id, sample.factor_id AS sample_factor_id
>> FROM sample JOIN cell ON cell.id = sample.factor_id
>> WHERE cell.name = :name_1
qry = session.query(Sample).filter(Sample.cell.has(Cell.name == "a_string"))
>> SELECT sample.id AS sample_id, sample.factor_id AS sample_factor_id
>> FROM sample
>> WHERE EXISTS (SELECT 1
>> FROM cell
>> WHERE cell.id = sample.factor_id AND cell.name = :name_1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.