php - CakePHP 3 保存 BelongsToMany 关联未知类型 ""错误

标签 php mysql cakephp cakephp-3.0

我一直在用头撞墙试图找出为什么我的电子邮件 (belongsToMany Guests (belongsToMany Emails)) 无法保存。当我尝试使用关联数据( guest )保存电子邮件模型时,它在 $this->Emails->save($email) 处失败,其中:

未知类型“”错误 无效参数异常

此时,我已经按照 CakeBookmarks 示例 ( http://book.cakephp.org/3.0/en/tutorials-and-examples/bookmarks/intro.html ) 进行了关系和编辑表单的 T 恤。甚至构建它并从中提取代码。

这是我项目中的相关代码,感谢任何帮助或猜测:

为 emails_guests 连接表创建语句:

CREATE TABLE emails_guests (
    email_id INT NOT NULL,
    guest_id INT NOT NULL,
    PRIMARY KEY (email_id, guest_id),
    FOREIGN KEY guest_key(guest_id) REFERENCES guests(id),
    FOREIGN KEY email_key(email_id) REFERENCES emails(id)
);

电子邮件表::初始化

public function initialize(array $config)
{
    // parent::initialize($config);

    $this->table('emails');
    $this->displayField('title');
    $this->primaryKey('id');
    $this->addBehavior('Timestamp');
    $this->belongsToMany('Guests', [
        'foreignKey' => 'email_id',
        'targetForeignKey' => 'guest_id',
        'joinTable' => 'emails_guests'
    ]);
}

客人表::初始化

public function initialize(array $config){
    parent::initialize($config);

    $this->table('guests');
    $this->displayField('name');
    $this->primaryKey('id');
    $this->addBehavior('Timestamp');
    $this->belongsTo('Invitations', [
        'foreignKey' => 'invitation_id'
    ]);
    $this->hasMany('Messages', [
        'foreignKey' => 'guest_id'
    ]);
    $this->belongsTo('SeatingGroups', [
        'foreignKey' => 'seating_group_id'
    ]);
    $this->belongsToMany('Emails', [
        'foreignKey' => 'guest_id',
        'targetForeignKey' => 'email_id',
        'joinTable' => 'emails_guests'
    ]);
}

电子邮件创建/更新 View manage.ctp

            <?= $this->Form->create($email); ?>
                <div class="row">
                    <div class="col-sm-12">
                        <?= $this->Form->input('title', ['id' => false]); ?>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-12">
                        <?= $this->Form->input('subject'); ?>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-12">
                        <?= $this->Form->input('message', ['class'=>'email-body']); ?>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-6">
                        <?= $this->Form->input(
                            'guests._ids',
                            [   
                                // 'type' => 'select',
                                'options' => $guests,
                                // 'multiple' => true,
                                // 'empty' => 'Please select the recipients.',
                                // 'label'=>'Recipients'
                            ]
                        ); ?>
                    </div>
                    <div class="col-sm-6">
                        <div class="row">
                            <div class="col-sm-12">
                                <?= $this->Form->input('send_by', ['id' => 'send-by', 'type' => 'text']); ?>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-sm-6">
                                <?= $this->Form->checkbox('now'); ?>
                                <label for="now">Send Now</label>
                            </div>
                            <div class="col-sm-6">
                                <?= $this->Form->input(
                                    __('Save'),
                                    [
                                        'type' => 'submit',
                                        'class' => 'inline',
                                        'label' => false
                                    ]
                                ) ?>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-12">
                    </div>
                </div>
                <div class="clearfix"></div>
            <?= $this->Form->end() ?>

最后是处理相关保存的 Controller :

public function manage($id = null) {
    $this->set('title', 'Manage Emails');

    if(isset($id)) {
        $email = $this->Emails->get($id, [
            'contain' => ['Guests']
        ]);
        $this->set('title', 'Email: ' . $email->title);
    } else {
        $email = $this->Emails->newEntity();
        $this->set('title', 'Create Email');
    }
    if ($this->request->is(['patch', 'post', 'put'])) {
        debug($email); 
        $email = $this->Emails->patchEntity($email, $this->request->data);
        debug($email); 
        debug($this->request->data);
        if ($this->Emails->save($email)) {

            if($email->now == true) {
                $this->process($email->id, $id);
            }
            $this->Flash->success('The email has been saved.');
            return $this->redirect(['action' => 'manage', $email->id]);
        } else {
            $this->Flash->error('The email could not be saved. Please, try again.');
        }
    }
    $guests = $this->Emails->Guests->find('list')->select(['id', 'first_name', 'last_name', 'email'])->toArray();

    $this->set('email', $email);
    $this->set('guests', $guests);
    $emails = $this->Emails->find();
    $this->set('emails', $this->paginate($emails));
    $this->set('_serialize', ['emails']);
}

当我保存一封电子邮件并选择一个或多个客人时的请求数据(这会触发 invalid type ""错误):

[
    'title' => 'Test Email Edit',
    'subject' => 'Hi! {{guest.first_name}}, we're testing some new features!2',
    'message' => 'Hi {{guest.first_name}} {{guest.last_name}},
We're testing some new features with recursive data. Let me tell you a bit about you:

Your seating group is: {{guest.seating_group.name}}.
Your invitation is: {{guest.invitation.name}}
Which we sent to: {{guest.invitation.address}}

Thanks! Hope this comes out okay... 
',
    'guests' => [
        '_ids' => [
            (int) 0 => '1'
        ]
    ],
    'send_by' => '',
    'now' => '0'
]

堆栈跟踪:

⟩ Cake\Database\Type::build
CORE/src/ORM/Table.php, line 1552
⟩ Cake\ORM\Table->_newId
CORE/src/ORM/Table.php, line 1489
⟩ Cake\ORM\Table->_insert
CORE/src/ORM/Table.php, line 1436
⟩ Cake\ORM\Table->_processSave
CORE/src/ORM/Table.php, line 1367
⟩ Cake\ORM\Table->Cake\ORM\{closure}
CORE/src/Database/Connection.php, line 561
⟩ Cake\Database\Connection->transactional
CORE/src/ORM/Table.php, line 1368
⟩ Cake\ORM\Table->save
CORE/src/ORM/Association/BelongsToMany.php, line 557
⟩ Cake\ORM\Association\BelongsToMany->_saveLinks
CORE/src/ORM/Association/BelongsToMany.php, line 506
⟩ Cake\ORM\Association\BelongsToMany->_saveTarget
CORE/src/ORM/Association/BelongsToMany.php, line 750
⟩ Cake\ORM\Association\BelongsToMany->Cake\ORM\Association\{closure}
CORE/src/Database/Connection.php, line 561
⟩ Cake\Database\Connection->transactional
CORE/src/ORM/Association/BelongsToMany.php, line 769
⟩ Cake\ORM\Association\BelongsToMany->replaceLinks
CORE/src/ORM/Association/BelongsToMany.php, line 445
⟩ Cake\ORM\Association\BelongsToMany->saveAssociated
CORE/src/ORM/AssociationCollection.php, line 254
⟩ Cake\ORM\AssociationCollection->_save
CORE/src/ORM/AssociationCollection.php, line 230
⟩ Cake\ORM\AssociationCollection->_saveAssociations
CORE/src/ORM/AssociationCollection.php, line 195
⟩ Cake\ORM\AssociationCollection->saveChildren
CORE/src/ORM/Table.php, line 1447
⟩ Cake\ORM\Table->_processSave
CORE/src/ORM/Table.php, line 1367
⟩ Cake\ORM\Table->Cake\ORM\{closure}
CORE/src/Database/Connection.php, line 561
⟩ Cake\Database\Connection->transactional
CORE/src/ORM/Table.php, line 1368
⟩ Cake\ORM\Table->save
APP/Controller/EmailsController.php, line 61
⟩ App\Controller\EmailsController->manage
[internal function]
⟩ call_user_func_array
CORE/src/Controller/Controller.php, line 411
⟩ Cake\Controller\Controller->invokeAction
CORE/src/Routing/Dispatcher.php, line 114
⟩ Cake\Routing\Dispatcher->_invoke
CORE/src/Routing/Dispatcher.php, line 87
⟩ Cake\Routing\Dispatcher->dispatch
ROOT/webroot/index.php, line 37

根据文档和示例,它应该可以正常工作。提前致谢!

最佳答案

看起来读取/缓存模式有问题,或者您为连接表类定义了不正确的主键。使用像您在此处显示的那样的复合主键,它永远不会到达代码中引发异常的地步。

删除 tmp/cache/models/,如果你有一个 EmailsGuestsTable 类,检查它是否通过 Table::primaryKey() 设置以及设置了什么,如果使用的话,应该是

['email_id', 'guest_id']

也许您的表最初有一个不同的主键,并且您之后对其进行了更改而没有清除缓存和/或更新相应的表类。

关于php - CakePHP 3 保存 BelongsToMany 关联未知类型 ""错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32017981/

相关文章:

PHP MySQL 的 INSERT INTO 问题

cakephp - 如何在cakephp中获取最后一个ID

cakePHP - 404- page not found 错误,在不同的机器上部署时

php - 重新编译时 Apache 破坏依赖错误消息 : Undefined symbols: "_apr_file_link

php - 在一台 Apache 服务器上的单独虚拟主机中运行 Apache mod_php 和 mod_fastcgi

php - 从 php 和在 Mysql Workbench 中查询特殊字符的结果不同

php - 如何选择 MySQL 中最常见的值?

输入选择表单上的 CakePHP 标签选项未按预期工作

php - Codeigniter 通过 CLI 将数组传递给 Controller

mysql - 使用 Ruby 将 mysql 结果导出到文件