yii - Saving Many-to-Many Relationships with TokenInput -
help me, oh mighty hive mind. you're hope.
i have been working on small app work i'm building around database (go figure). while have managed save relationship data more manually iterating through data, creating new model each, , saving information, know there must cleaner way this:
foreach($keys $k) { //build model associate keyword $k $facts_keyword=new factskeyword; $facts_keyword['fact_id']=$model->id; $facts_keyword['keyword_id']=$k; if(!$facts_keyword->save()) //check errors on saving echo "failure save facts_keywords"; }
to make work, have made model reference table between tables facts
, keywords
. reference table has 2 columns facts_id
, keywords_id
. using tokeninput plugin yii input keywords associated given fact. relevant view code here:
<div id="keywords" class="row"> <?php echo $form->labelex($keyword,'keywords'); ?> <?php $this->widget('ext.tokeninput.tokeninput', array( 'model'=>$keyword, 'attribute'=>'name', 'url'=>array('keyword/searchkeys'), 'options' => array( 'allowcreation'=>false, 'preventduplicates'=>true, 'resultsformatter'=>'js:function(item){ return "<li><p>" + item.name + "</p></li>" }', 'prepopulate'=>$key, 'theme'=>'facebook', 'minchars'=>2, ) )); ?> <?php echo $form->error($keyword,'name'); ?> </div>
the relationship fact model looks this: 'keywords' => array(self::many_many, 'keyword', 'facts_keywords(fact_id, keyword_id)')'
how can save information view in cleaner way? have tried change 'model'=>$keyword
'model'=>$fact
, changing 'attribute'=>'name'
'attribute'=>'sources'
gives error: trim() expects parameter 1 string, array given
doing wrong?
just use extension: activerecord-relation-behavior
Comments
Post a Comment