最初に簡単な説明。モデル化する必要があります:アカウントとユーザー、およびそのアカウントの結合テーブル。モデルには、各モデルに多対多の関連付けがあります。
ユーザーモデル:
'Account' => array(
'className' => 'Account',
'joinTable' => 'accounts_users',
'foreignKey' => 'user_id',
'associationForeignKey' => 'account_id',
'unique' => true,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
)
アカウントモデル:
'User' => array(
'className' => 'User',
'joinTable' => 'accounts_users',
'foreignKey' => 'account_id',
'associationForeignKey' => 'user_id',
'unique' => true,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
)
今、私はこの2つの間の関係を、既存のすべてのエントリからの結合テーブルacccounts_usersに手動で保存しようとしています。ここに私のコードがあります
$account = base64_decode($this->params['pass']['0']);
$token = $this->params['pass']['1'];
if($user = $this->User->findByToken($token))
{
// ZUr test zwecken
# $this->User->query(" INSERT INTO accounts_users (account_id ,user_id) VALUES (222, 223); ");
$aId = $this->Account->findById($account);
$this->data['User'][0]['user_id'] = $user['User']['id'];
$this->data['Account'][0]['account_id'] = $aId['Account']['id'];
$this->User->bindModel(array(
'hasMany' => array('AccountsUser')
));
$this->User->saveAll($this->data, array('validate' => false));
print_r('gefunden'); die;
$this->Redirect->flashSuccess('Account Invitation successfull. Log In!', array('controller' => 'users', 'action' => 'login'));
}
else
{
print_r('nicht gefunden'); die;
// user nicht gefunden zum login umleiten
$this->Redirect->flashWarning('Account Invitation error. Please try again!', array('controller' => 'users', 'action' => 'login'));
}
結果はaccounts_usersテーブルの新しいエントリですが、user_idは0です。正しく渡されたためにユーザーIDが欠落している理由がわかりません。データ配列にいくつかのIDを手動で渡しても、ユーザーIDなしでaccount_idだけを書き込みます。
アップデート
モデルを少し試して、アカウントモデルを介してaccounts_usersにデータを保存しました。更新されたコードを参照してください。
$this->data['User']['id'] = $user['User']['id'];
$this->data['Account']['id'] = 33; #$aId['Account']['id'];
$this->Account->AccountsUser->create();
$this->Account->saveAll($this->data, array('validate' => false));
そのため、スクリプトは両方のIDを挿入しますが、同じアカウントIDを持つ別のユーザーからのエントリがある場合、そのユーザーは上書きされます。他のものはすべて機能します。新しいユーザーの軸アカウントIDを使用して新しいエントリを作成する方法を考えている人はいますか?
これは私が得るmysqlクエリです:
UPDATE accounts
SET id
=33WHERE accounts
。id
= 33
SELECT AccountsUser
。user_id
FROMASWHERE 。accounts_users
_ AccountsUser
_ = 33AccountsUser
account_id
DELETE AccountsUser
FROMASWHERE 。accounts_users
_ AccountsUser
_ = 33 ANDAccountsUser
account_id
INSERT INTO accounts_users
(account_id
、user_id
)VALUES(33、 '32')
アイデアを出す人はなぜですか?前もって感謝します