1

私は CakePHP を初めて使用し、英語が母国語ではないため、質問が明確でない場合は申し訳ありません。とにかく、 DeveloperGameの 2 つのモデルがあります。

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

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

ゲームと開発者の ID を実際に知らなくても、ゲームと開発者の間に関係があることを示す game_id フィールドと developer_id フィールドのみを持つテーブル developer_games に新しい行を追加するにはどうすればよいでしょうか。同時。私は 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);

不明な点がある場合はお知らせください。明確にいたします。私は長い間この問題に苦しんできたので、私が得られる助けに感謝します。ありがとう!

4

2 に答える 2

0

これを読んでください: http://book.cakephp.org/view/1044/hasAndBelongsToMany-HABTM 「hasAndBelongsToMany」はあなたが望む関係です。関連付けは Cake が処理するので、結合テーブルのモデルは必要ありません。

于 2011-03-30T08:02:47.687 に答える
0

誤解していなければ、論理図の多対多のゲームと開発者の関係は、[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 に答える