[英]CakePHP save model and associated model
我有一個用戶模型。
它具有包含如下形式的注冊視圖:
echo $this->Form->create('User',array(NULL,NULL,'class' => 'signinform'));
echo $this->Form->input('first_name');
...
echo $this->Form->end('Create Account');
提交表單時,其保存如下:
$this->User->save($this->data)
這可行。
我在數據庫中添加了一個名為addresses
的表,其中的字段user_id
是users.id
的外鍵
我輸入了我的用戶模型:
var $hasMany = 'Address';
我將這樣的字段添加到注冊表單:
echo $this->Form->input('Address.city');
我希望這可以在地址表中創建一個新條目,並將其與新用戶關聯。 它不會創建新用戶,但不會在地址表中放置任何內容。
我嘗試將保存功能從save
更改為saveAll
:
$this->User->saveAll($this->data)
現在什么也得不到保存。
我究竟做錯了什么?
CakePHP保存需要更多的工作來跨關系保存。 這是文檔中的示例 。
<?php
function add() {
if (!empty($this->data)) {
// We can save the User data:
// it should be in $this->data['User']
$user = $this->User->save($this->data);
// If the user was saved, Now we add this information to the data
// and save the Profile.
if (!empty($user)) {
// The ID of the newly created user has been set
// as $this->User->id.
$this->data['Profile']['user_id'] = $this->User->id;
// Because our User hasOne Profile, we can access
// the Profile model through the User model:
$this->User->Profile->save($this->data);
}
}
}
?>
當您進行多個數據庫更改時,應該考慮使用事務來使它們一起成功或失敗。 如果您不想使用事務,請考慮當請求部分失敗時將顯示給用戶的內容。 還請考慮將數據庫保留在什么狀態,以及如何恢復。
您可能還需要將其放入“地址”模型中:
var $belongsTo = 'User';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.