CakePHP将模型关联添加到数据库表中

我是CakePHP的新手,英语不是我的第一语言,所以如果我的问题不清楚,我会道歉。无论如何,我有两个模型:开发者和游戏。
<?php
class Developer extends AppModel
{
    var $name = 'Developer';
    var $belongsTo = array('Game');
}
?>
<?php
class Game extends AppModel
{
    var $name = 'Game';
    var $hasMany = array('Developer');
}
?>
我怎样才能在developer_games表中添加一个新行,该表只有game_id和developer_id字段,表明游戏和开发人员之间存在关系,而实际上并不知道游戏和开发人员的ID,因为他们是在同时。我认为CakePHP能够为我做这个,但它不会在developer_games表中添加新行。保存数据后,我是否必须检索游戏和开发人员的“id”字段,然后手动将关系模型数据保存到developer_games表中? 这是我用来向数据库添加新游戏和开发人员的代码:
$data = $this->Game->saveAll(array(
    'Game' => array(
        'game_id' => $data['GameId'],
        'game_name' => $data['GameName'],
    ),
    'Developer' => array(
        'Developer' => array(
            'username' => $_POST['dev_username'],
            'password_hash' => $_POST['dev_password'],
        ),
    ),
));
$this->Game->saveAll($data);
如果我不清楚某事,请告诉我,我会澄清。我很长一段时间一直在努力解决这个问题,所以我会感激任何帮助。谢谢!     
已邀请:
如果我没有误解,逻辑图中多对多的游戏 - 开发者关系,则它应该是[游戏] -1:N- [赋值] -N:1- [开发人员] 这里的分配是你的“developer_games”表,我建议你重命名表以方便 根据您的场景,CakePHP中推荐的实现将是3个模型类。
<?php
class Developer extends AppModel
{
    var $name = 'Developer';
    var $hasMany = array('Assignment');
}
?>

<?php
class Game extends AppModel
{
    var $name = 'Game';
    var $hasMany = array('Assignment');
}
?>

<?php
class Assignment extends AppModel
{
    var $name = 'Assignment';
    var $belongsTo = array('Game','Developer');
}
?>
这是添加新分配的代码
//retrieved submitted data --> $data
$data = $this->data;

// this is for the case you want to insert into 3 tables at a same time
$newGame = $this->Game->create();
$newGame = array(
    'Game'=> array(
        'name' => $data['Game']['name']
    )
);
$this->Game->save($newGame);
$newGameId = $this->Game->getLastInsertId();

$newDev = $this->Developer->create();
$newDev = array(
    'Developer'=> array(
        'name' => $data['Developer']['name']
    )
);
$this->Developer->save($newDev);
$newDevId = $this->Developer->getLastInsertId();

/**
* or if you already have Game Id, and Developer Id, then just load it on, and 
* put it in the statement below, to create a new Assignment
**/
$newAssignment = $this->Assignment->create();
$newAssignment = array(
    'Assignment' => array(
        'game_id' => $newGameId,
        'developer_id' => $newDevId,
    )
);
$this->Assignment->save($newAssignment);
    
请读一读:http://book.cakephp.org/view/1044/hasAndBelongsToMany-HABTM “hasAndBelongsToMany”是你想要的关系。 Cake负责关联,并且您不需要连接表的模型。     

要回复问题请先登录注册