yii relations trough one table

66 views Asked by At

is it possible in Yii 1.1.14 to connect these tables using one "object_rel" table?

object_rel:

  • id
  • owner_id (e.g. location record id)
  • owner_type (e.g. 2 = location)
  • slave_id (e.g. program record id)
  • slave_type (e.g. 1 = program)

location(type = 2):

  • id
  • ...

program(type = 1):

  • id
  • ...

category(type = 3):

  • id
  • ...

or i have to write some custom fancy stuff?

I have tried MANY_TO_MANY with no luck...

1

There are 1 answers

0
nielsdg On

Unfortunately, I don't think this is possible with relations, as they require you to specify the model-class. However, you could define something like this in your model for object_rel:

private static $modelTypes = array(
    1 => Program::model(),
    2 => Location::model(),
    3 => Category::model(),
);


public static function getOwner($object)
{
    $data = self::$db->createCommand()
               ->select('owner_id, owner_type')
               ->from('object_rel')
               ->where('owner_id = :object_id', array(':object_id' => $object->id))
    ->queryRow(true); // assuming every object only has one owner

    // no results found
    if ($data === false) {
        return false;
    }

    $model = self::$modelTypes[data['owner_type']];
    return $model->findByPk(data['owner_id']);
}