[英]How to save this data in cakePHP?
I have a User
Model and a Boarder
Model, Not every User is a Boarder but Every Boarder is a User. 我有一个
User
模型和一个Boarder
模型, 不是每个用户都是寄宿生,而是每个寄宿生都是用户。
User model 用户模型
class User extends AppModel
{
public $primaryKey = "user_id";
public $hasMany = 'Boarder';
}
Boarder model 寄宿生模型
class Boarder extends AppModel
{
public $belongsTo = 'User';
}
add.ctp of my Boarders View 我的寄宿生视图的add.ctp
<?php
echo $this->Form->create('Boarder', array('role' => 'form', 'novalidate' => true));
echo $this->Form->input('user_name');
echo $this->Form->input('bdr_home_address');
echo $this->Form->end();
?>
So during submit, add function in controller will now receive an array something like this 因此,在提交过程中,控制器中的add函数现在将收到一个类似这样的数组
Array
(
[Boarder] => Array
(
[user_name] => 'John',
[bdr_home_address] => 'Some Street, Some City'
)
)
[user_name]
will be saved in Users Model while [bdr_home_address]
will be saved in Boarders model. [user_name]
将保存在Users模型中,而[bdr_home_address]
将保存在[bdr_home_address]
模型中。 as indicated in my $this->Form->create
the request will be directed to BoardersController, action add. 如我的
$this->Form->create
,请求将被定向到BoardersController,动作添加。 So how will I be able to save this? 那么我将如何保存呢?
BoardersController BoardersController
class BoardersController extends AppController
{
public function add()
{
}
}
If every Boarder
is a User
, the Boarder
table should include a user_id
field. 如果每个
Boarder
都是一个User
,那么Boarder
表应该包含一个user_id
字段。
The add.ctp
form can look like add.ctp
表单如下所示
<?php
echo $this->Form->create('Boarder', array('role' => 'form', 'novalidate' => true));
echo $this->Form->input('User.username');
echo $this->Form->input('Boarder.home_address');
echo $this->Form->submit();
echo $this->Form->end();
?>
The add
function from the controller is: 控制器的
add
功能为:
public function add()
{
if ($this->request->is('post')) {
debug($this->request->data);
if ($this->Boarder->saveAssociated($this->request->data)) {
// saved
} else {
// not saved
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.