Cakephp无法在插入时自动生成记录ID

时间:2014-07-16 16:54:58

标签: php mysql cakephp

我在蛋糕php中有一个非常简单的连接模型。我遇到了一个错误,其中插入的每个新记录的ID是""。

 <?php


 App::uses('AppModel', 'Model');
/**
 * Subscriber Model
 *
 * @property ChallengeMember $ChallengeMember
 * @property Activity $Activity
 */
class Subscriber extends AppModel {


    //The Associations below have been created with all possible keys, those that are not needed can be removed

/**
 * belongsTo associations
 *
 * @var array
 */
    public $belongsTo = array(
        'ChallengeMember' => array(
            'className' => 'ChallengeMember',
            'foreignKey' => 'challenge_member_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'Activity' => array(
            'className' => 'Activity',
            'foreignKey' => 'activity_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );
}

这就是表格的样子:

  public $fields = array(
        'id' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 36, 'key' => 'primary', 'collate' => 'latin1_swedish_ci', 'charset' => 'latin1'),
        'activity_id' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 37, 'collate' => 'latin1_swedish_ci', 'charset' => 'latin1'),
        'challenge_member_id' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 37, 'collate' => 'latin1_swedish_ci', 'charset' => 'latin1'),
        'indexes' => array(

        ),
        'tableParameters' => array('charset' => 'latin1', 'collate' => 'latin1_swedish_ci', 'engine' => 'InnoDB')
    );

测试时,

$this->Subscriber->create(array('challenge_member_id' => 'test123456','ChallengeMember.first_time_in_dash' => '1'));
$this->Subscriber->save();
Debugger::dump($this->Subscriber->find('all'));

输出

array(
        'Subscriber' => array(
            'id' => '',
            'challenge_member_id' => 'test123456',
            'activity_id' => '',
            'created' => '2014-07-16 18:45:14'
        )
        ........

正如你所看到的那样,蛋糕会自动失败,因为这对我的其他模特来说是不合时宜的。有任何想法吗 ?我重新烘焙了模型和测试夹具,但没有快乐!

1 个答案:

答案 0 :(得分:0)

好的,所以我从来没有完全理解这个问题,这个问题似乎只与名为&#34; Subscriber&#34;的表有关。每个其他表都有一个ID字段定义为:

'id' => array('type' => 'string', 'null' => false, 'default' => null, 'length' => 36, 'key' => 'primary', 'collate' => 'latin1_swedish_ci', 'charset' => 'latin1')

在Model :: save()上,cakephp auto会生成如下所示的ID:

53c4fe0c-c38c-4915-a056-111fd1f54a2f.

最后,我将订阅者ID字段设置为&#34; INT(11)自动递增&#34;,让mysql负责密钥生成。这解决了这个问题。