2016-03-01 29 views
0

我一直在使用SQLAlchemy的ORMSQLAlchemy的刪除在兩個方向級聯(不ORM)

class HasId(object): 
    @declared_attr 
    def id(cls): 
     return Column('id', Integer, Sequence('test_id_seq'), primary_key=True) 
    ... 

class TestParent(HasId, Model): 
    __tablename__ = 'tests' 
    discriminator = Column(String(50)) 
    __mapper_args__ = {'polymorphic_on': discriminator} 
    ... 


class FooTest(TestParent): 
    __tablename__ = 'footests' 
    __mapper_args__ = {'polymorphic_identity': 'footests'} 
    id = Column(Integer, ForeignKey('tests.id'), primary_key=True) 
    parent_id = Column(Integer, ForeignKey('footests.id', ondelete='CASCADE')) 
    children = relationship('FooTest', 
          foreign_keys='FooTest.parent_id', 
          lazy='joined', 
          join_depth=2, 
          cascade='save-update, merge, delete, delete-orphan') 
    ... 

不使用ORM時,當我從tests(該TestParent模型)刪除行定義的一些車型,footests中的對應行被刪除。都好。

我希望能夠從footests外的ORM的刪除一行,並在tests相應的行被刪除。這基本上是讓級聯在相反的方向上工作。

這可能是ORM之外的嗎?還有另一種方法來思考這個問題嗎? (數據庫引擎是MySQL/Mariadb)與ORM

+0

您如何插入和刪除? – univerio

+0

@univerio,我目前正在使用GUI與數據庫交互。我編輯了我的問題,詢問在沒有ORM的情況下這是否可能。 –

回答

1

如果添加這應該只是工作/刪除:

>>> foo = FooTest() 
>>> session.add(foo) 
>>> session.flush() 
>>> list(session.execute("SELECT * FROM tests;")) 
[(u'footests', 1)] 
>>> list(session.execute("SELECT * FROM footests;")) 
[(1, None)] 
>>> session.delete(foo) 
>>> session.flush() 
>>> list(session.execute("SELECT * FROM tests;")) 
[] 
>>> list(session.execute("SELECT * FROM footests;")) 
[] 
+0

你認爲有沒有辦法在MySQL中定義這個級聯(不使用ORM)?在開發過程中,我花了很多時間使用數據庫gui。 –

+0

@BrianLeach你可以添加一個[觸發器](http://dev.mysql.com/doc/refman/5.7/en/create-trigger.html)來做到這一點。 – univerio