1

我有 3 张桌子:

  • 带有(company_id)主键的 Company 表
  • 带有(company_id, url)主键和外键的页表返回公司
  • (company_id, attr_key)带有主键和返回公司的外键的 Attr 表。

我的问题是如何使用 Attr 中的现有列构建从 Attr 到 Page 的 ManyToOne 关系,即company_idurl

from elixir import Entity, has_field, setup_all, ManyToOne, OneToMany, Field, Unicode, using_options
from sqlalchemy.orm import relation

class Company(Entity):
    using_options(tablename='company')
    company_id = Field(Unicode(32), primary_key=True)
    has_field('display_name', Unicode(255))
    pages = OneToMany('Page')

class Page(Entity):
    using_options(tablename='page')
    company = ManyToOne('Company', colname='company_id', primary_key=True)
    url = Field(Unicode(255), primary_key=True)

class Attr(Entity):
    using_options(tablename='attr')
    company = ManyToOne('Company', colname='company_id', primary_key=True)
    attr_key = Field(Unicode(255), primary_key=True)
    url = Field(Unicode(255)) #, ForeignKey('page.url'))
    # page = ManyToOne('Page', colname=["company_id", "url"])
    # page = relation(Page, backref='attrs', foreign_keys=["company_id", "url"], primaryjoin=and_(url==Page.url_part, company_id==Page.company_id))

我已经注释掉了一些失败的尝试。

最后,Attr.company_id 需要成为 Page 和 Company 的外键(以及 Attr 中的主键)。

这可能吗?

4

1 回答 1

2

是的,你可以这样做。Elixir 没有内置的方法来做到这一点,但因为它是 SQLAlchemy 上的一个薄包装器,你可以说服它这样做。因为 Elixir 没有重用现有列的多对一关系的概念,您需要将 GenericProperty 与 SQLAlchemy 关系属性一起使用,并使用表选项添加外键。下面的代码应该做你想做的事:

from elixir import Entity, has_field, setup_all, ManyToOne, OneToMany, Field, Unicode, using_options, using_table_options, GenericProperty
from sqlalchemy.orm import relation
from sqlalchemy import ForeignKeyConstraint

class Company(Entity):
    using_options(tablename='company')

    company_id = Field(Unicode(32), primary_key=True)
    display_name = Field(Unicode(255))
    pages = OneToMany('Page')

class Page(Entity):
    using_options(tablename='page')

    company = ManyToOne('Company', colname='company_id', primary_key=True)
    url = Field(Unicode(255), primary_key=True)
    attrs = OneToMany('Attr')

class Attr(Entity):
    using_options(tablename='attr')

    page = ManyToOne('Page', colname=['company_id', 'url'], primary_key=True)
    attr_key = Field(Unicode(255), primary_key=True)

    using_table_options(ForeignKeyConstraint(['company_id'], ['company.company_id']))
    company = GenericProperty(relation(Company))
于 2009-05-14T23:34:12.103 回答