我一直在研究 sqlalchemy 的自引用表。我已经多次阅读文档,但仍然难以理解remote_side. 有人可以画一张图或用一个类比来帮助解释这个概念吗?我认为可视化是一种更好的方法,但任何帮助都会受到赞赏。谢谢。
编辑:顺便说一句,在我看来,这个词remote有点模糊,因为它可以从不同的角度解释。就像leftand一样rigt,这真的取决于你面对的方向,我的right可能是你的left。我对此不太有信心,但我猜想将名称从remote_sideto 链接起来many_side可能会有所帮助?如果我在这里错了,请纠正我。
When specifying a relationship between two tables, one of the tables has a foreign key. This foreign key "marks" one or more columns as being "connected" to columns in another table.
When specifying relationships in SQLAlchemy, we're using the term "remote" when talking about the columns "on the other side" of the foreign-key columns. Or, whichever columns the "foreign" columns are "linked to".
For example, consider a "Customer" table with a "Order" table:
+---------------+ +------------------+
| Customer | | Order |
+---------------+ +------------------+
| customer-id | ------- | customer_id [FK] |
| name | | order_id |
+---------------+ +------------------+
Run Code Online (Sandbox Code Playgroud)
Assume the order table has a relationship with the customer table via the customer_id column.
In that case, the foreign key will be located on the Order table, and it will "point to" the Customer.customer_id column.
As we established earlier, the "remote side" in SQLAlchemy is the "other side" of the foreign key.
So in this particular example, the "remote side" is the Customer.customer_id column.
When working with self-referential tables the concept is the same. You have some columns defined as foreign keys "pointing to" other columns (but in the same table this time). But the concept of "foreign" and "remote" remains the same for SA. You just have to adapt it as necessary for the self-referential relationship.
由于似乎没有人对这样的初学者概念感兴趣,因此我将尽力解决这个问题。
首先想象两张相同的桌子,一张在左边,一张在右边。现在深呼吸。
通过指定remote_side外键引用的属性,实际上建立了从本地到远程的关系。
现在的问题是,我可以指定remote_side外键属性本身吗?让我们通过做一个实验来看看差异:
class Employee(Base):
__tablename__ = 'employees'
id = Column(Integer(), primary_key=True)
manager_id = Column(Integer(), ForeignKey('employees.id'))
name = Column(String(255), nullable=False)
Manager = relationship("Employee", backref=backref('reports'), remote_side=[manager_id])
Run Code Online (Sandbox Code Playgroud)
运行这个,我们得到这个错误:
sqlalchemy.exc.ArgumentError: Employee.Manager and back-reference Employee.reports are both of the same direction symbol('ONETOMANY'). Did you mean to set `remote_side` on the many-to-one side?
Run Code Online (Sandbox Code Playgroud)
显然,这是行不通的。我们被困在一种单向暴政之中。
| 归档时间: |
|
| 查看次数: |
1640 次 |
| 最近记录: |