Relations

Maybe my question seems silly, but for me it is very relevant. =)

Well… I created two tables.




CREATE TABLE `tbl_users` (

  `id` int(11) NOT NULL AUTO_INCREMENT,

  `username` varchar(20) NOT NULL,

  `password` varchar(128) NOT NULL,

  `email` varchar(128) NOT NULL,

  `activkey` varchar(128) NOT NULL DEFAULT '',

  `createtime` int(10) NOT NULL DEFAULT '0',

  `lastvisit` int(10) NOT NULL DEFAULT '0',

  `superuser` int(1) NOT NULL DEFAULT '0',

  `status` int(1) NOT NULL DEFAULT '0',

  PRIMARY KEY (`id`),

  UNIQUE KEY `username` (`username`),

  UNIQUE KEY `email` (`email`),

  KEY `status` (`status`),

  KEY `superuser` (`superuser`)

) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;

 




CREATE TABLE tbl_post (

    post_id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,

    title VARCHAR(128) NOT NULL,

    post VARCHAR(128) NOT NULL,

    author_id INTEGER NOT NULL, 

    CONSTRAINT FK_post_author FOREIGN KEY (author_id)

                REFERENCES tbl_users (id) ON DELETE CASCADE ON UPDATE RESTRICT

) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

 

Have class Post extends CActiveRecord

and class User extends CActiveRecord ( modul user-yii )

Post.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(

                   'author' => array(self::BELONGS_TO, 'User', 'author_id')

        );

    }

 

Creating a post and that’s what we see




CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`yii`.`tbl_post`, CONSTRAINT `FK_post_author` FOREIGN KEY (`author_id`) REFERENCES `tbl_users` (`id`) ON DELETE CASCADE). The SQL statement executed was: INSERT INTO `tbl_post` (`title`, `post`) VALUES (:yp0, :yp1)

 

What did i miss ?

when create you post , you must give the use_id to it:

         $model->author_id  = Yii::app()->user->id; 

error you saw is :

…The SQL statement executed was: INSERT INTO tbl_post (title, post) VALUES (:yp0, :yp1)

there are only ‘title’ and ‘post’ assigned but no author_id :lol: