yiimany-to-manygiiyii-cactiverecordcactiverecord

Recursive Many to many relationship with Yii


I have a recursive many to many relationship with objective. My Relational model is:

CREATE TABLE master.objectives
(
  id serial NOT NULL,
  name character varying(100),
  CONSTRAINT pkey_objectives PRIMARY KEY (id),
  CONSTRAINT fk_objectives_perspective FOREIGN KEY (perspective_id)
      REFERENCES master.perspective (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)

CREATE TABLE master.relatedobjectives
(
  parent integer NOT NULL,
  child integer NOT NULL,
  CONSTRAINT relatedobjectives_pkey PRIMARY KEY (parent, child),
  CONSTRAINT fk_child_objectives FOREIGN KEY (child)
      REFERENCES master.objectives (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT fk_paret_objectives FOREIGN KEY (parent)
      REFERENCES master.objectives (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)

I have been generated my model in Yii framework with gii as shows belows:

Objective.php

public function relations() {
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
    return array(
        'parents' => array(self::HAS_MANY, 'Relatedobjectives', 'parent'),
        'children' => array(self::HAS_MANY, 'Relatedobjectives', 'child'),
    );
}

objectives/_form.php

<div class="row">
    <?= $form->checkBoxList($model,'parents', 
                            CHtml::listData(Objective::model()->findAll(array('order' => 'id')), 'id', 'name')
            ) ?>
</div>

In the view when I submit the form not save the relationship in relatedobjectives table.

What am I doing wrong?


Solution

  • Related models aren't saved along with the parent model. You must save them manually in the parents beforeSave() or afterSave() hooks. There are also some extensions which can do this automatically. Look here for some info on that topic.