From: <sub...@co...> - 2006-11-17 22:10:35
|
Author: rflosi Date: 2006-11-17 15:10:29 -0700 (Fri, 17 Nov 2006) New Revision: 2093 Modified: SQLObject/docs/FAQ.txt Log: added 'How can I define my own intermediate table in my Many-to-Many relationship?' example to FAQ Modified: SQLObject/docs/FAQ.txt =================================================================== --- SQLObject/docs/FAQ.txt 2006-11-15 16:38:58 UTC (rev 2092) +++ SQLObject/docs/FAQ.txt 2006-11-17 22:10:29 UTC (rev 2093) @@ -103,6 +103,47 @@ .. _SQLBuilder: SQLBuilder.html .. _example: SQLObject.html#how-can-i-join-a-table-with-itself + +How can I define my own intermediate table in my Many-to-Many relationship? +--------------------------------------------------------------------------- + +We'll expand on the User and Role example and define our own UserRoles class which +will be the intermediate table for the User and Role Many-to-Many relationship. + +Example:: + + >>> class User(SQLObject): + ... class sqlmeta: + ... table = "user_table" + ... username = StringCol(alternateID=True, length=20) + ... roles = SQLRelatedJoin('Role', intermediateTable='user_roles', createRelatedTable=False) + + >>> class Role(SQLObject): + ... name = StringCol(alternateID=True, length=20) + ... users = SQLRelatedJoin('User', intermediateTable='user_roles', createRelatedTable=False) + + >>> class UserRoles(SQLObject): + ... class sqlmeta: + ... table = "user_roles" + ... user = ForeignKey('User', notNull=True, cascade=True) + ... role = ForeignKey('Role', notNull=True, cascade=True) + ... active = BoolCol(notNull=True, default=False) + ... unique = index.DatabaseIndex(user, role, unique=True) + +.. note:: + In User and Role, SQLRelatedJoin is used with createRelatedTable=False + so the intermediate table is not created automatically. We also set the + intermediate table name with intermediateTable='user_roles'. + UserRoles is the definition of our intermediate table. + UserRoles creates a unique index to make sure we don't have duplicate + data in the database. + We also added an extra field called active which has a boolean value. + The active column might be used to activate/deactivate a given role for + a user in this example. + Another common field to add in this an intermediate table might be a sort + field. + + How Does Inheritance Work? -------------------------- |