Cakephp根据保存请求数据

时间:2014-05-01 16:57:47

标签: php mysql cakephp

我的问题是关于如何将表单上请求的数据保存到两个表中,并知道我将生成的user_id。 这些表是链接的,但第一个表(用户)上有一个字段(id)是自动生成的(顺序号),我需要在第二个表(地址)上插入该值。

For example:
In my view.ctp:
     -- Users
                        <div>Name</div>
                        <div><?php echo $this->Form2->input('name'); ?></div>
                        <div>Surname</div>
                        <div><?php echo $this->Form2->input('surname'); ?></div>
    -- Contacts
                        <div>Phone</div>
                        <div><?php echo $this->Form2->input('phone'); ?></div>
                        <div>Address</div>
                        <div><?php echo $this->Form2->input('address'); ?></div>

这是我的数据库:

CREATE TABLE IF NOT EXISTS users (
    id int NOT NULL AUTO_INCREMENT,
    name varchar(50),
    surname varchar(50),
    PRIMARY KEY (id))

CREATE TABLE IF NOT EXISTS contactos (
  id int(10) NOT NULL AUTO_INCREMENT,
  user_id int(10) NOT NULL,
  tipo enum('Entrega', 'Facturação'),
  PRIMARY KEY (id),
  FOREIGN KEY (user_id) REFERENCES users(id));

有什么建议吗?

提前致谢。

3 个答案:

答案 0 :(得分:0)

如果您的model's已关联,则会自动保存相关的模型数据 -

<div>Name</div>
<?php echo $this->Form->create('User');?>
<div><?php echo $this->Form->input('name'); ?></div>
<div>Surname</div>
<div><?php echo $this->Form->input('surname'); ?></div>

<div>Phone</div>
<div><?php echo $this->Form->input('Contact.phone'); ?></div>
<div>Address</div>
<div><?php echo $this->Form->input('Contact.address'); ?></div>
<?php echo $this->Form->end('Save');

答案 1 :(得分:0)

查看:

   <div>Name</div>
    <?php echo $this->Form->create('User');?>
    <div><?php echo $this->Form->input('name'); ?></div>
    <div>Surname</div>
    <div><?php echo $this->Form->input('surname'); ?></div>        
    <div>Phone</div>
    <div><?php echo $this->Form->input('Contact.phone'); ?></div>
    <div>Address</div>
    <div><?php echo $this->Form->input('Contact.address'); ?></div>
    <?php echo $this->Form->end('Save');

<强>控制器:

  $this->User->Contact->saveAll($this->request->data); // TO save ABOVE FORM DATA

答案 2 :(得分:0)

好的我理解你的问题。你也可以这样做。首先在第一个表User中插入值,如下所示

  $data = array();
  $data['name'] = $this->request->data('name');
  $data['surname'] = $this->request->data('surname');
  $this->User->save($data);

然后获取最后插入的用户ID

$id = $this->User->getInsertID();

现在插入另一个表

 $contactdata = array();
  $contactdata['user_id'] = $id;
 $contactdata['phone'] = $this->request->data('Contact.phone');
  $contactdata['address'] = $this->request->data('Contact.address');

  $this->Contact->save( $contactdata);

这是一种替代方式。