Foreign Key Relationship Issue

Hi,

i have a model(media.php) and it has genre checkbox from genre model.While creating media form i am submitting the $model->gener in media model,but genre is not in my DB table .For this i have a mapping table like

mediaId reference from media table and genreId from genre table.

My question is i want to save selected checkbox from model media,insted of saving it to media table i want to save it mapping table media_genre.

Media relation:-return array(

		'tblGenres' => array(self::MANY_MANY, 'Genre', 'tbl_media_genre(mediaId, genreId)'),


	);

Genre relation:-

return array(

		'tblMedias' => array(self::MANY_MANY, 'Media', 'tbl_media_genre(genreId, mediaId)'),


	);

Thanks in advance.

[color="#006400"]/* Moved from "Miscellaneous" to "General Discussion for Yii 1.1.x" */[/color]

http://www.yiiframework.com/forum/index.php/topic/16936-many-to-many/page__view__findpost__p__84170

3960

Media.php

Error:-

include(genreId.php) [<a href=‘function.include’>function.include</a>]: failed to open stream: No such file or directory

My DB is like:-

CREATE TABLE IF NOT EXISTS tbl_media (

id int(11) NOT NULL AUTO_INCREMENT,

name varchar(100) NOT NULL,

path varchar(150) NOT NULL,

user_id int(11) NOT NULL,

create_time datetime DEFAULT NULL,

PRIMARY KEY (id)

)


CREATE TABLE IF NOT EXISTS tbl_genre (

id int(11) NOT NULL AUTO_INCREMENT,

genre_name varchar(150) NOT NULL,

PRIMARY KEY (id)

)


CREATE TABLE IF NOT EXISTS tbl_media_genre (

mediaId int(11) NOT NULL,

genreId int(11) NOT NULL,

PRIMARY KEY (mediaId,genreId),

KEY FK_genre_media (genreId)

)


genreId is not saved in tbl_Media.But submitted from media.php model and saving genreId direct into tbl_media_genre ,which is my mapping table.genre is my checkBoxList.

I am not sure if this is a right approach or not.

Now i want result in tbl_media_genre like:-

mediaId genreId

1 2

1 4

1 5

2 1

What line in the error coming from?

Made a few small modifications - but haven’t tested though.





<?php


/**

 * This is the model class for table "tbl_media".

 *

 * The followings are the available columns in table 'tbl_media':

 * @property integer $id

 * @property string $name

 * @property string $path

 * @property integer $user_id

 * @property string $create_time

 *

 * The followings are the available model relations:

 * @property Genre[] $genres

 */

class Media extends CActiveRecord

{

        public $file;

        public $genreIds = array();

	/**

	 * Returns the static model of the specified AR class.

	 * @param string $className active record class name.

	 * @return Media the static model class

	 */

	public function behaviors()

        {

            return array(

                'CAdvancedArBehavior' => array(

                    'class' => 'application.extensions.CAdvancedArBehavior'));

        }

        

        public static function model($className=__CLASS__)

	{

		return parent::model($className);

	}


	/**

	 * @return string the associated database table name

	 */

	public function tableName()

	{

		return 'tbl_media';

	}


	/**

	 * @return array validation rules for model attributes.

	 */

	public function rules()

	{

		// NOTE: you should only define rules for those attributes that

		// will receive user inputs.

		return array(

			array('name, path, genreIds, user_id', 'required'),

			array('user_id', 'numerical', 'integerOnly'=>true),

			array('name', 'length', 'max'=>100),

			array('path', 'length', 'max'=>150),

			array('create_time, genreIds', 'safe'),

			// The following rule is used by search().

			// Please remove those attributes that should not be searched.

			array('id, name, path, genreIds, user_id, create_time', 'safe', 'on'=>'search'),

		);

	}


	/**

	 * @return array relational rules.

	 */

	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(

			'genres' => array(self::MANY_MANY, 'Genre', 'tbl_media_genre(mediaId, genreId)'),

		);

	}


	/**

	 * @return array customized attribute labels (name=>label)

	 */

	public function attributeLabels()

	{

		return array(

			'id' => 'ID',

			'name' => 'Name',

			'path' => 'Path',

			'user_id' => 'User',

			'create_time' => 'Create Time',

			'genreIds' => 'Genres',

                        

		);

	}


	/**

	 * Retrieves a list of models based on the current search/filter conditions.

	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.

	 */

	public function search()

	{

		// Warning: Please modify the following code to remove attributes that

		// should not be searched.


		$criteria=new CDbCriteria;


		$criteria->compare('id',$this->id);

		$criteria->compare('name',$this->name,true);

		$criteria->compare('path',$this->path,true);

		$criteria->compare('user_id',$this->user_id);

		$criteria->compare('create_time',$this->create_time,true);


		return new CActiveDataProvider($this, array(

			'criteria'=>$criteria,

		));

	}

        

	public function getGenreOptions()

	{

		$uglyGenres = CHtml::listData(Genre::model()->findAll(), 'id', 'genre_name');


		$beautifulGenres = array();

		

		foreach($uglyGenres as $id => $name)

		{

			$beautifulGenres[] = ucfirst($name);

		}

		

		return $beautifulGenres;

	}

	

	public function afterFind()

	{

		if(!empty($this->genres))

		{

			foreach($this->genres as $n => $genre)

				$this->genreIds[] = $genre->id;

		}

		

		parent::afterFind();

	 }

        

}



Thank you Very very much.Really appreciated you help.

As i was stuck in this from 2days,i got my own way .

Called a method to insert ,after saving the model.

controller :-

if($model->save())

                            {   


                                &#036;uploded = &#036;file-&gt;saveAs(&#036;dir.&quot;&#092;&#092;&quot;.&#036;model-&gt;name.&quot;.mp3&quot;);


                                Media::model()-&gt;associateMediaToGenre(&#036;model-&gt;id,&#036;model-&gt;genre);


                                &#036;this-&gt;redirect(array('view','id'=&gt;&#036;model-&gt;id));


                            }

Model:-

public function associateMediaToGenre($mediaId,$genreId)

    {


        foreach(&#036;genreId as &#036;value)


        &#036;genre_ids[] = &#036;value;


           


        for(&#036;i=0;&#036;i&lt;count(&#036;genre_ids);&#036;i++)


            {


                &#036;sql = &quot;INSERT INTO tbl_media_genre(mediaId,genreId) VALUES(&#036;mediaId,&#036;genre_ids[&#036;i])&quot;;


                &#036;command = Yii::app()-&gt;db-&gt;createCommand(&#036;sql);


                &#036;command-&gt;bindValue(&quot;:mediaId&quot;,&#036;mediaId,PDO::PARAM_INT);


                &#036;command-&gt;bindValue(&quot;:genreId&quot;,&#036;genre_ids[&#036;i],PDO::PARAM_INT);


                &#036;command-&gt;execute();


            }


            return true;


        


    } 

Again thanks a ton.Will be taking your assistance :)