保存与Yii有很多关系的模型

时间:2012-05-15 11:02:21

标签: php yii many-to-many relationship

我有3个这样的表:用户(ID,名称)|教程(ID,Tutcontent)| UserTutorial(ID,IDUser,IDTutorial)。我使用此代码来保存模型

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

它不会在mydatabase中保存新记录

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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);

答案 2 :(得分:-1)

$user = User::model()->findByPk(1);
$tutorial = Tutorial::model()->findAll("id=2");     
$user->**RELATION_ALIAS** = $tutorial;
$user->save();