如何创建与其自身具有 ManyToMany 关系的 Elixir 类

发布于 2024-11-25 10:07:12 字数 284 浏览 0 评论 0原文

我很难思考这个问题,但基本上我想创建一个名为 Assets 的 Elixir 类,它可以拥有许多资产。所以,它可能看起来像这样(但这显然不起作用):

class Asset(Entity):
    has_field('Name', Unicode)
    has_many('Assets', of_kind='Asset', inverse='Assets')

所以,我希望能够有一个“扁平”的资产系统,但我不确定它是否可能,甚至是最好的。

有办法做到这一点吗?

I'm having trouble thinking this through, but basically I want to create an Elixir class called Assets which can have many Assets. So, it could look something like this (but this doesn't work, obviously):

class Asset(Entity):
    has_field('Name', Unicode)
    has_many('Assets', of_kind='Asset', inverse='Assets')

So, I would love to be able to have a 'flat' system of Assets, but I'm not sure its possible or even best.

Is there a way of doing this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

还在原地等你 2024-12-02 10:07:12

我对 Elixir 不太了解,但这是使用 SQLAlchemy 声明式来做到这一点的方法。希望 Elixir 的定义足够相似,这对您有帮助。

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

class Employee(Base):
  __tablename__ = 'employee'
  id = Column(Integer, primary_key=True)
  name = Column(String(64), nullable=False)
Employee.manager_id = Column(Integer, ForeignKey(Employee.id))
Employee.manager = relationship(Employee, backref='subordinates',
    remote_side=Employee.id)

请注意,managermanager_id 字段是“猴子修补”的,因为您无法在类定义中进行自引用。

I'm not savvy in Elixir but this is how you can do it using SQLAlchemy declarative. Hopefully the Elixir definition will be similar enough that this help you.

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

class Employee(Base):
  __tablename__ = 'employee'
  id = Column(Integer, primary_key=True)
  name = Column(String(64), nullable=False)
Employee.manager_id = Column(Integer, ForeignKey(Employee.id))
Employee.manager = relationship(Employee, backref='subordinates',
    remote_side=Employee.id)

Note that the manager and manager_id fields are "monkey-patched" because you cannot make self-references within a class definition.

初心 2024-12-02 10:07:12

感谢@wberry 的一些见解,我明白了。在 Elixir 中:

class Asset(Entity):
    has_field('Name', Unicode)
    Assets = ManyToMany('Asset')

使用它,我可以做这样的疯狂事情:

a1 = Asset(Name=u'Asset 1')
a2 = Asset(Name=u'Asset 2')
a3 = Asset(Name=u'Asset 3')

a1.Assets=[a1,a2,a3]

而且它有效。我喜欢它!

I figured it out, thanks to some insight from @wberry. In Elixir:

class Asset(Entity):
    has_field('Name', Unicode)
    Assets = ManyToMany('Asset')

Using that, I can do crazy things like this:

a1 = Asset(Name=u'Asset 1')
a2 = Asset(Name=u'Asset 2')
a3 = Asset(Name=u'Asset 3')

a1.Assets=[a1,a2,a3]

And it works. I love it!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文