1

我是 CakePHP 的新手,英语不是我的第一语言,所以如果我的问题不清楚,我深表歉意。无论如何,我有两个模型:DeveloperGame

<?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);

如果我有什么不清楚的地方,请告诉我,我会澄清的。我一直在努力解决这个问题,所以我会很感激我能得到的任何帮助。谢谢!

4

2 回答 2

0

如果我没有误解,逻辑图中多对多的 Game-Developer 关系,那么它应该是 [Game]-1:N-[Assignment]-N:1-[Developer] 这里的赋值是你的“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);
于 2011-03-30T02:12:31.213 回答
0

Please have a read on this: http://book.cakephp.org/view/1044/hasAndBelongsToMany-HABTM "hasAndBelongsToMany" is the relationship you want. Cake takes care about the associations and you don't need a model for the join table.

于 2011-03-30T08:02:47.687 回答