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

时间:2011-03-30 01:30:35

标签: php cakephp cakephp-appmodel

我是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表中添加新行。我是否必须在保存数据后检索Game和Developer的'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);

如果我对某些事情不清楚,请告诉我,我会澄清。我很长一段时间一直在努力解决这个问题,所以我会感激任何帮助。谢谢!

2 个答案:

答案 0 :(得分:0)

如果我没有误解,逻辑图中多对多的游戏 - 开发者关系,则它应该是[游戏] -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);

答案 1 :(得分:0)

请仔细阅读:http://book.cakephp.org/view/1044/hasAndBelongsToMany-HABTM “hasAndBelongsToMany”是你想要的关系。 Cake负责关联,你不需要连接表的模型。