我试图在第三个表格'中保存关系。这是代码:
控制器保存操作:
$relations = $_POST['VideoCaptions']['countries'];
$model->attachBehavior('ManyToManyRelationBehavior', array(
'class' => 'ManyToManyRelationBehavior',
'modelNameRelation' => 'Relations',
'firstField' => 'video_captions',
'secondField' => 'video_countries',
'relationList' => $relations,
));
ManyToManyRelationBehavior类afterSave操作:
if (is_array($this->relationList)){
$model_ = $this->modelNameRelation;
$model_::model()->deleteAll("first_field
= :firstField AND first_field_value
= :firstFieldValue AND second_field
= :secondField", array(
":firstField" => $this->firstField,
":firstFieldValue" => $this->owner->id,
":secondField" => $this->secondField
));
foreach ($this->relationList as $value){
$model_ = new $this->modelNameRelation;
$model_->first_field = $this->firstField;
$model_->first_field_value = $this->owner->id;
$model_->second_field = $this->secondField;
$model_->second_field_value = intval($value);
if (!$model_->save()) return false;
}
}
return true;
var_dump($ model_)返回该模型存在,但$ model-> save()不保存表格中的任何数据'关系'。我不明白为什么。有人可以帮忙吗?
答案 0 :(得分:1)
您为此“modelNameRelation”设置了哪些验证?您应该尝试使用insert()方法而不是save()并检查它是否可以工作?保存第一个验证然后调用insert()或update()方法。
答案 1 :(得分:0)
解决:
foreach ($this->relationList as $value){
$model = new $this->modelNameRelation;
$model->first_field = $this->firstField;
$model->first_field_value = $this->owner->id;
$model->second_field = $this->secondField;
$model->second_field_value = intval($value);
Yii::app()->db->createCommand()->insert($model->tableName(), $model->attributes);
}