Handle Many to many relation for one table


I have a table tasks, and each task can be dependent from other tasks, and have dependant tasks as well.

So I’ve another table for many-to-many relationship task2task with fields: id, ref_task_before and ref_task_after.

So is there a way to handle this relation in Yii were one table has many to many relation with the same table?

Maybe something like:

public function relations()


    return array(

        'taskBefore' => array(self::MANY_MANY, 'Task', 'task2task(REF_TASK_BEFORE, REF_TASK_AFTER)'),

        'taskAfter' => array(self::MANY_MANY, 'Task', 'task2task(REF_TASK_BEFORE, REF_TASK_AFTER)')



but with additional identifiers.


I think I’ve found solution by setting relations this way:

'taskBefore' => array(self::MANY_MANY, 'Task', 'task2task(REF_TASK_AFTER, REF_TASK_BEFORE)'),

'taskAfter' => array(self::MANY_MANY, 'Task', 'task2task(REF_TASK_BEFORE, REF_TASK_AFTER)')

You are only going to need one model.

You are actually trying to store a tree, so take a look at this:


The algorithm you’ll be using here is called Modified Preorder Tree Traversal - I am not sure if Yii has anything built-in, or an extension, but it should be straight forward to do this.

Using a single model.;)

Found it:


Man, thanks for your answer.

In my case each node (i.e. task) can have more than one parent nodes (i.e. task can have several tasks that should be done before), and each node can have more than one child nodes (i.e. several tasks can be done only after finishing this task), so I think I still need an additional table to map relations.