【发布时间】:2013-03-08 16:04:03
【问题描述】:
首先是一个简短的描述。我必须模型:帐户和用户以及它的连接表accounts_users。模型在每个模型上都有一个 habtm 关联:
用户模型:
'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' => ''
)
现在我试图将这两者之间的关系手动保存到连接表 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,它只写了 account_id 而没有用户 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 查询:
更新accounts SET id = 33 其中accounts.id = 33
选择AccountsUser.user_id FROM accounts_users AS AccountsUser WHERE AccountsUser.account_id = 33
从accounts_users 删除AccountsUser 为AccountsUser 其中AccountsUser.account_id = 33 和
插入accounts_users (account_id,user_id) 值 (33,'32')
任何想法为什么?提前致谢
【问题讨论】:
-
看看“HasMany Through”,而不是这种疯狂的绑定模型……等等;)
-
你使用的是 cakephp 2.x 吗?
-
不,我使用的是 cake 1.3。有什么区别吗?
-
嘿,戴夫,你能解释一下你的意思吗?
标签: cakephp model has-and-belongs-to-many jointable