2012-05-15 61 views
3

我有3个这样的表格:User(ID,Name)|教程(ID,Tutcontent)| UserTutorial(ID,IDUser,IDTutorial)。我用这个代码来保存模型保存与Yii多对多关系的模型

$user = User::model()->findByPk(1); 
    $tutorial = Tutorial::model()->findByPk(1); 
    $userTutorial = new UserTutorial; 
    $userTutorial->IDUser = $user->ID; 
    $userTutorial->IDTutorial = $tutorial->ID; 
    $userTutorial->save(); 

它不保存MyDatabase的新纪录

回答

1

这是你的任务非常有用的扩展:CAdvancedArBehavior
不要忘了正确定义模型关系:A great tutorial about relations

+0

非常感谢,但我仍然遇到问题。 我将'CAdvancedArBehavior.php'复制到扩展目录,在'main.php''import'=> array('application.extensions.CAdvancedArBehavior')中修改,在'Post.php'关系中添加'categories'=> array( self :: MANY_MANY,'Category','categorypost(postid,categoryid)'),在它下面我加\t public function behaviors(){return array('CAdvancedArBehavior'=> array('class'=>'application.extensions .CAdvancedArBehavior'));} 在'PostController.php'中添加公共函数actionNewPost(){ $ post = new Post(); $ post-> categories = Category :: model() - > findAll(); $ post-> save();} –

1

试试这个..

$user = User::model()->findByPk(1); 
    $tutorial = Tutorial::model()->findByPk(1); 
    $userTutorial = new UserTutorial; 
    $userTutorial->IDUser = $user->ID; 
    $userTutorial->IDTutorial = $tutorial->ID; 
    $userTutorial->save(false); 
-1
$user = User::model()->findByPk(1); 
$tutorial = Tutorial::model()->findAll("id=2");  
$user->**RELATION_ALIAS** = $tutorial; 
$user->save();