草庐IT

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

coder 2023-10-12 原文

我一直在用头撞墙试图找出为什么我的电子邮件 (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 - CakePHP 3 保存 BelongsToMany 关联未知类型 ""错误的更多相关文章

  1. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  2. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  3. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

  4. ruby - 续集在添加关联时访问many_to_many连接表 - 2

    我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以

  5. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  6. ruby-on-rails - 相关表上的范围为 "WHERE ... LIKE" - 2

    我正在尝试从Postgresql表(table1)中获取数据,该表由另一个相关表(property)的字段(table2)过滤。在纯SQL中,我会这样编写查询:SELECT*FROMtable1JOINtable2USING(table2_id)WHEREtable2.propertyLIKE'query%'这工作正常:scope:my_scope,->(query){includes(:table2).where("table2.property":query)}但我真正需要的是使用LIKE运算符进行过滤,而不是严格相等。然而,这是行不通的:scope:my_scope,->(que

  7. ruby-on-rails - Ruby 检查日期时间是否为 iso8601 并保存 - 2

    我需要检查DateTime是否采用有效的ISO8601格式。喜欢:#iso8601?我检查了ruby​​是否有特定方法,但没有找到。目前我正在使用date.iso8601==date来检查这个。有什么好的方法吗?编辑解释我的环境,并改变问题的范围。因此,我的项目将使用jsapiFullCalendar,这就是我需要iso8601字符串格式的原因。我想知道更好或正确的方法是什么,以正确的格式将日期保存在数据库中,或者让ActiveRecord完成它们的工作并在我需要时间信息时对其进行操作。 最佳答案 我不太明白你的问题。我假设您想检查

  8. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  9. ruby - 安装 Ruby 时遇到问题(无法下载资源 "readline--patch") - 2

    当我尝试安装Ruby时遇到此错误。我试过查看this和this但无济于事➜~brewinstallrubyWarning:YouareusingOSX10.12.Wedonotprovidesupportforthispre-releaseversion.Youmayencounterbuildfailuresorotherbreakages.Pleasecreatepull-requestsinsteadoffilingissues.==>Installingdependenciesforruby:readline,libyaml,makedepend==>Installingrub

  10. ruby - RVM "ERROR: Unable to checkout branch ."单用户 - 2

    我在新的Debian6VirtualBoxVM上安装RVM时遇到问题。我已经安装了所有需要的包并使用下载了安装脚本(curl-shttps://rvm.beginrescueend.com/install/rvm)>rvm,但以单个用户身份运行时bashrvm我收到以下错误消息:ERROR:Unabletocheckoutbranch.安装在这里停止,并且(据我所知)没有安装RVM的任何文件。如果我以root身份运行脚本(对于多用户安装),我会收到另一条消息:Successfullycheckedoutbranch''安装程序继续并指示成功,但未添加.rvm目录,甚至在修改我的.bas

随机推荐