CakePHP创建新记录的id始终为1并覆盖现有记录

时间:2011-09-10 14:06:36

标签: php cakephp

我已经构建了一个CakePHP应用程序,用于为客户创建约会,每当我尝试为客户创建约会时,它总是覆盖任何具有相同ID的现有约会。在数据库中将ID设置为AI,这样它应该自动增量,但事实并非如此。

这是我的控制器动作:

function admin_add($client_id)
{
    $this->set('client_id', $client_id);

    $this->set('client', $this->Appointment->Client->find('first', array('conditions' => array('Client.id' => $client_id))));

    $this->set('doctors', $this->Appointment->Doctor->find(
      'list',
      array(
        'fields' => array('Doctor.name'),
        'order' => array('Doctor.firstname', 'Doctor.lastname')
      )
    ));

    if (!empty($this->data))
    {
        if ($this->Appointment->save($this->data))
        {
            $this->Session->setFlash('Your post has been saved.');
            $this->redirect(array('admin' => true, 'controller' => 'appointments', 'action' => 'index'));
        }
    }
}

这是我的模特:

class Appointment extends AppModel
{
    var $name = 'Appointment';

    var $useTable = 'appointments';

    var $belongsTo = array('Client','Doctor');
}

最后我对表单的看法:

<h1>Book Appointment <em>for</em> <?php echo $client['Client']['firstname'] . " " . $client['Client']['lastname']; ?></h1>

<?php echo $this->Form->create('Appointment', array('url' => array('admin'=>true,'controller'=>'appointments','action'=>'add',$client_id))); ?>

<fieldset id="post-form">
    <ul>
        <li>
            <?php echo $this->Form->input('client_id',array('type'=>'hidden','value'=>$client_id)); ?>

            <?php echo $this->Form->input('doctor_id',array('label'=>'<strong>Choose Doctor</strong>'),$doctors); ?>
        </li>
        <li>
            <?php echo $this->Form->input('datetime',array('label'=>'<strong>Date and Time</strong>')); ?>
        </li>
        <li>
            <?php echo $this->Form->input('treatment',array('label'=>'<strong>Treatment</strong>')); ?>
        </li>
        <li class="sep clearfix">
            <input class="submit" type="submit" name="submit" value="Book Appointment" />
            <?php echo $this->Html->link('Cancel',array('admin'=>true,'controller'=>'clients','action'=>'view',$client_id)); ?>
        </li>
    </ul>
</fieldset>

<?php echo $this->Form->end(); ?>

2 个答案:

答案 0 :(得分:1)

因为您在Form-&gt; create()中有client_id,因此表单从添加更改为编辑。这是Cake的(恼人的)自动化之一。您可以在保存之前取消设置该ID字段($ this-&gt; data)

答案 1 :(得分:0)

将此添加到视图中可以解决问题:

<?php echo $this->Form->input('id', array('type' => 'hidden')); ?>

但为什么我需要这样做?很明显,数据库能够用整数填充该字段,它只是没有自动递增:/

相关问题