سؤال

Help me, Oh Mighty Hive Mind. You're my only hope.

I have been working on a small app for work that I'm building around a database (go figure). While I have managed to save relationship data more manually by iterating through the data, creating a new model for each, and then saving that information, I know there must be a cleaner way than this:

foreach($keys as $k) {
  //Build the model to associate with keyword $k
  $facts_keyword=new FactsKeyword;
  $facts_keyword['fact_id']=$model->id;
  $facts_keyword['keyword_id']=$k;
  if(!$facts_keyword->save()) //Check for errors on saving
    echo "FAILURE TO SAVE FACTS_KEYWORDS";
}

To make this work, I have made a model for the reference table between the tables facts and keywords. The reference table simply has two columns facts_id and keywords_id. I am using the TokenInput plugin for Yii to input the keywords that are associated with a given fact. The relevant view code is 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 from the fact model looks like this: 'keywords' => array(self::MANY_MANY, 'Keyword', 'facts_keywords(fact_id, keyword_id)')'

How can I save the information from the my view in a cleaner way? I have tried to change 'model'=>$keyword to 'model'=>$fact and changing 'attribute'=>'name' to 'attribute'=>'sources' That gives this error: trim() expects parameter 1 to be string, array given What am I doing wrong?

هل كانت مفيدة؟

المحلول

Just use this extension: activerecord-relation-behavior

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top