[英]CakePHP add model association into database table
我是CakePHP的新手,英语不是我的母语,所以如果我的问题不清楚,我深表歉意。 无论如何,我有两个模型: Developer和Game 。
<?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);
如果我不清楚某些事情,请告诉我,我会澄清。 很长时间以来,我一直在努力解决这个问题,因此,我将不胜感激。 谢谢!
如果我没有误解逻辑图上多对多游戏与开发人员的关系,那么应该是[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);
请阅读以下内容: http ://book.cakephp.org/view/1044/hasAndBelongsToMany-HABTM“ hasAndBelongsToMany”是您想要的关系。 Cake会关心关联,因此您不需要联接表模型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.