i have a table with 2 foreign keys that map to the same primary key of another table. the problem i'm facing is that these two foreign keys could be independent values, however, they always get set to the same thing when using SQLAlchemy.
tables (shorthanded):
CREATE TABLE table1 (
userid INT NOT NULL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
UNIQUE KEY(name)
);
CREATE TABLE table2 (
taskid INT NOT NULL PRIMARY KEY,
userid INT,
ownerid INT,
task VARCHAR(255) NOT NULL,
FOREIGN KEY (userid) REFERENCES users (userid),
FOREIGN KEY (ownerid) REFERENCES users (userid)
);
i'm using the classical mapper from sqlalchemy and my class definition is:
class User:
def __init__( self, name ):
self.name = name
class Task:
def __init__( self, task, ownerid ):
self.task = task
self.ownerid = ownerid
the ownerid and userid could be different i.e. ownerid is the user who owns the task and userid is the user that created the task.
i've created mappings:
users_table = sqlalchemy.Table( 'users', self.metadata, autoload=True )
tasks_table = sqlalchemy.Table( 'tasks', self.metadata, autoload=True )
sqlalchemy.orm.mapper( User, users_table, properties= {
'tasks': sqlalchemy.orm.relationship(Task) } )
sqlalchemy.orm.mapper( Task, tasks_table, properties {
'user': sqlalchemy.orm.relationship( User, primaryjoin=tasks_table.c.userid==users_table.c.userid ),
'owner': sqlalchemy.orm.relationship( User, primaryjoin=tasks_table.c.ownerid==users_table.c.userid ) } )
and the syntax for working with these objects is something akin to:
case 1:
u1 = User('burt')
t1 = Task( 'buy milk', u1.userid ) # this case is that the task is assigned to self
case 2:
u2 = User('kelly')
t2 = Task( 'review code', u1.userid ) # assign to burt, creator is kelly
in case 2, i'm having an issue here as the ownerid always equals the userid, in this case the ownerid and userid are 2 (for kelly) always.