Yii Framework Forum: Foreign Key Relationship Issue - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Foreign Key Relationship Issue Rate Topic: ***** 1 Votes

#1 User is offline   shivanshu 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 29
  • Joined: 17-March 13
  • Location:India

Posted 17 March 2013 - 04:33 AM

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.
0

#2 User is offline   softark 

  • Keep It Simple
  • Yii
  • Group: Moderators
  • Posts: 2,082
  • Joined: 16-February 11
  • Location:Japan

Posted 17 March 2013 - 08:27 AM

/* Moved from "Miscellaneous" to "General Discussion for Yii 1.1.x" */
0

#3 User is offline   waterloomatt 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 545
  • Joined: 09-April 10

Posted 17 March 2013 - 09:19 AM

http://www.yiiframew...dpost__p__84170
0

#4 User is offline   shivanshu 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 29
  • Joined: 17-March 13
  • Location:India

Posted 18 March 2013 - 02:04 AM

Attached File  Media.php (3.62K)
Number of downloads: 2

View Postshivanshu, on 18 March 2013 - 02:04 AM, said:

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

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

#5 User is offline   shivanshu 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 29
  • Joined: 17-March 13
  • Location:India

Posted 18 March 2013 - 02:48 AM

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
0

#6 User is offline   waterloomatt 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 545
  • Joined: 09-April 10

Posted 18 March 2013 - 06:41 AM

View Postshivanshu, on 18 March 2013 - 02:04 AM, said:

Attachment Media.php
Error:-
include(genreId.php) [<a href='function.include'>function.include</a>]: failed to open stream: No such file or directory


What line in the error coming from?
0

#7 User is offline   waterloomatt 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 545
  • Joined: 09-April 10

Posted 18 March 2013 - 06:56 AM

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();
	 }
        
}

0

#8 User is offline   shivanshu 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 29
  • Joined: 17-March 13
  • Location:India

Posted 19 March 2013 - 06:58 AM

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())
{
$uploded = $file->saveAs($dir."\\".$model->name.".mp3");
Media::model()->associateMediaToGenre($model->id,$model->genre);
$this->redirect(array('view','id'=>$model->id));
}

Model:-

public function associateMediaToGenre($mediaId,$genreId)
{
foreach($genreId as $value)
$genre_ids[] = $value;

for($i=0;$i<count($genre_ids);$i++)
{
$sql = "INSERT INTO tbl_media_genre(mediaId,genreId) VALUES($mediaId,$genre_ids[$i])";
$command = Yii::app()->db->createCommand($sql);
$command->bindValue(":mediaId",$mediaId,PDO::PARAM_INT);
$command->bindValue(":genreId",$genre_ids[$i],PDO::PARAM_INT);
$command->execute();
}
return true;

}

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

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users