草庐IT

php - Laravel:无法在生产中添加外键约束

coder 2023-10-12 原文

我正在开发一个 Laravel 项目并创建了模型,当我在我的计算机(我正在开发的计算机上)上运行迁移时,一切正常,甚至是表之间的关系。当我将代码上传到生产服务器并在创建关系的位置运行迁移时出现问题。

在下面的代码中,我留下了一些注释行,这些行是我为解决问题而尝试做的事情,但没有任何效果。

  • 我尝试将两个表的表引擎都设置为 innoDB,但没有成功。
  • 我试图在两个表上将 id 数据类型设置为 increments,并且 deviceTypeID 列将用作外键,我将其定义为 unsignedinteger 但它不起作用。

  • 我什至检查了两台计算机上的 PHP、Composer、Doctrine/dbal 和 mysql 版本,它们是相同的(或几乎相同)。

开发计算机:
PHP: 7.3
作曲:1.8.6
MySQL服务器:5.7.23
学说/dbal:2.9

生产服务器:
PHP: 7.3
作曲:1.9
MySQL服务器:5.7.25
学说/dbal:2.9
(它运行 Ubuntu Server 18.04)

  • 我还尝试在另一台计算机上运行该项目,看看我是否遇到同样的错误,但没有出现,一切正常。

  • 我还运行了这个查询“alter table devices add constraint devices_devicetypeid_foreign foreign key (deviceTypeID) references devicestype(id) on delete cascade"没有直接在 mysql 命令行上的所有引号并且它有效。所以问题与用户权限无关。

当它尝试在 AddRelationDevicesDeviceType 上运行代码时,它总是在生产环境中崩溃

class CreateDevicesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('devices', function (Blueprint $table) {
            //$table->engine = 'innoDB'
            $table->bigIncrements('id');
            //$table->increments('id');
            $table->unsignedBigInteger('deviceTypeID');
            //$table->integer('deviceTypeID')->unsigned();
            $table->timestamps();
        });
    }
}

class CreateDevicesTypeTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('devicesType', function (Blueprint $table) {
           //$table->engine = 'innoDB'
            $table->bigIncrements('id');
            //$table->increments('id');
            $table->string("Device Type");
            $table->text("Description");
            $table->timestamps();
        });
    }
}


class AddRelationDevicesDeviceType extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('devices', function($table) {
            $table->foreign('deviceTypeID')
                            ->references('id')->on('devicesType')
                            ->onDelete('cascade');
        });
    }
}

这是错误:

Illuminate\Database\QueryException  : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `devices` add constraint `devices_devicetypeid_foreign` foreign key (`deviceTypeID`) references `devicestype`(`id`) on delete cascade) at /var/www/html/MYPROJECT/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664
    660|         // If an exception occurs when attempting to run a query, we'll format the error
    661|         // message to include the bindings with SQL, which will make this exception a
    662|         // lot more helpful to the developer instead of just the databa se's errors.
    663|         catch (Exception $e) {
  > 664|             throw new QueryException(
    665|                 $query, $this->prepareBindings($bindings), $e
    666|             );
    667|         }
    668|

  Exception trace:

  1   Doctrine\DBAL\Driver\PDOException::("SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint") /var/www/html/MYPROJECT/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php:119

  2   PDOException::("SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint") /var/www/html/MYPROJECT/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php:117

最佳答案

我想出了解决问题的方法。

问题是当我运行第一次迁移时创建表“devicesType” MySQL 将表名更改为小写,所以它最终变成了“devicestype”,当我在上次迁移中尝试引用该表时我创建了 Laravel 找不到表的关系。

我的开发服务器不区分大小写,而我的生产服务器区分大小写。

我还将“deviceTypeID”从“unsignedBigInteger”更改为“bigInteger”,并使用“unsigned”方法指定无符号类型

如果对某人有用,这是我的新代码:

class CreateDevicesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('devices', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('deviceTypeID')->unsigned();
            $table->timestamps();
        });
    }
}

class CreateDevicesTypeTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('devicestype', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string("Device Type");
            $table->text("Description");
            $table->timestamps();
        });
    }
}


class AddRelationDevicesDeviceType extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('devices', function($table) {
            $table->foreign('deviceTypeID')
                            ->references('id')->on('devicestype')
                            ->onDelete('cascade');
        });
    }
}

关于php - Laravel:无法在生产中添加外键约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57420112/

有关php - Laravel:无法在生产中添加外键约束的更多相关文章

  1. ruby - 我需要将 Bundler 本身添加到 Gemfile 中吗? - 2

    当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/

  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-on-rails - 无法使用 Rails 3.2 创建插件? - 2

    我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby​​1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在

  4. ruby - 将 Bootstrap Less 添加到 Sinatra - 2

    我有一个ModularSinatra应用程序,我正在尝试将Bootstrap添加到应用程序中。get'/bootstrap/application.css'doless:"bootstrap/bootstrap"end我在views/bootstrap中有所有less文件,包括bootstrap.less。我收到这个错误:Less::ParseErrorat/bootstrap/application.css'reset.less'wasn'tfound.Bootstrap.less的第一行是://CSSReset@import"reset.less";我尝试了所有不同的路径格式,但它

  5. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

  6. ruby-on-rails - 无法在centos上安装therubyracer(V8和GCC出错) - 2

    我正在尝试在我的centos服务器上安装therubyracer,但遇到了麻烦。$geminstalltherubyracerBuildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingtherubyracer:ERROR:Failedtobuildgemnativeextension./usr/local/rvm/rubies/ruby-1.9.3-p125/bin/rubyextconf.rbcheckingformain()in-lpthread...yescheckingforv8.h...no***e

  7. 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].有没有一种方法可以

  8. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

  9. ruby-on-rails - s3_direct_upload 在生产服务器中不工作 - 2

    在Rails4.0.2中,我使用s3_direct_upload和aws-sdkgems直接为s3存储桶上传文件。在开发环境中它工作正常,但在生产环境中它会抛出如下错误,ActionView::Template::Error(noimplicitconversionofnilintoString)在View中,create_cv_url,:id=>"s3_uploader",:key=>"cv_uploads/{unique_id}/${filename}",:key_starts_with=>"cv_uploads/",:callback_param=>"cv[direct_uplo

  10. ruby - 无法覆盖 irb 中的 to_s - 2

    我在pry中定义了一个函数:to_s,但我无法调用它。这个方法去哪里了,怎么调用?pry(main)>defto_spry(main)*'hello'pry(main)*endpry(main)>to_s=>"main"我的ruby版本是2.1.2看了一些答案和搜索后,我认为我得到了正确的答案:这个方法用在什么地方?在irb或pry中定义方法时,会转到Object.instance_methods[1]pry(main)>defto_s[1]pry(main)*'hello'[1]pry(main)*end=>:to_s[2]pry(main)>defhello[2]pry(main)

随机推荐