Error At $Model->Save() On Relation Table

ER diagram

4356

ER Diagram.jpg

Mysql table







CREATE TABLE `p_cluster` (

  `id` int(11) NOT NULL AUTO_INCREMENT,

  `parent_id` int(11) DEFAULT NULL,

  `name` varchar(45) NOT NULL,

  `desc` varchar(128) DEFAULT NULL,

  `depth` int(11) NOT NULL DEFAULT '0',

  PRIMARY KEY (`id`),

  KEY `fk_p_cluster_parent_idx` (`parent_id`),

  CONSTRAINT `fk_p_cluster_parent` FOREIGN KEY (`parent_id`) REFERENCES `p_cluster` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION

) ENGINE=InnoDB DEFAULT CHARSET=latin1;




CREATE TABLE `p_item` (

  `id` int(11) NOT NULL AUTO_INCREMENT,

  `cluster_id` int(11) NOT NULL,

  `product_id` int(11) NOT NULL,

  PRIMARY KEY (`id`),

  KEY `fk_p_item_cluster_idx` (`cluster_id`),

  CONSTRAINT `fk_p_item_cluster` FOREIGN KEY (`cluster_id`) REFERENCES `p_cluster` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION

) ENGINE=InnoDB DEFAULT CHARSET=latin1;


CREATE TABLE `p_attribute` (

  `id` int(11) NOT NULL AUTO_INCREMENT,

  `name` varchar(45) NOT NULL,

  `desc` varchar(128) DEFAULT NULL,

  `type_id` int(11) NOT NULL,

  `cluster_id` int(11) NOT NULL,

  PRIMARY KEY (`id`),

  KEY `fk_p_attribute_cluster_idx` (`cluster_id`),

  CONSTRAINT `fk_p_attribute_cluster` FOREIGN KEY (`cluster_id`) REFERENCES `p_cluster` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION

) ENGINE=InnoDB DEFAULT CHARSET=latin1



Generate model and CRUD via gii (with no error)

for p_cluster Table

Try to entry data

4357

form.jpg

I’m not sure what’s wrong, but i fixed it with:

in Model (commented on relations)





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(

			'parent' => array(self::BELONGS_TO, 'Cluster', 'parent_id'),

			'clusters' => array(self::HAS_MANY, 'Cluster', 'parent_id'),

			//'attributes' => array(self::HAS_MANY, 'Attribute', 'cluster_id'),

			//'items' => array(self::HAS_MANY, 'Item', 'cluster_id'),

		);

	}



OR

in Controller (add extra line on actionCreate and actionUpdate)





	if (isset($_POST['Cluster'])) {

			$model->attributes = $_POST['Cluster'];


			/* Must use this per field, on actionUpdate too */

			$model->name = $_POST['Cluster']['name'];

			/* $model->desc = $_POST... 

	         */


			if ($model->save())

				$this->redirect(array('view', 'id' => $model->id));

		}



is it bug?

LinuxMint 13, Apache, Chrome & Firefox, Yii ver 1.1.13

[/size]

I use Table Prefix to create Model in gii

so… p_cluster table -> Cluster model

I tried without Table Prefix, and it work normaly :D

May be some one already have same issue?

[size="2"]




public function relations()

	{

        ...

     		'attributes' => array(self::HAS_MANY, 'Attribute', 'cluster_id'),

        ...

	}



OK, I know :)

Don’t use attribute as table name / attributes as relations

your model will not be saved [/size]

hope can help someone