【问题标题】:Laravel 4 Schema Builder - Circular ReferenceLaravel 4 Schema Builder - 循环参考
【发布时间】:2015-03-16 18:43:02
【问题描述】:

我有一个用户表和一个公司表

Users 表有一个引用 Companies.id 的列“company_id”,而 Companies 有一个引用 Users.id 的列“assignation”

显然,无论我首先尝试创建哪个表,我都会收到一条错误消息,指出它无法创建引用约束,因为另一个表不存在。

我可以手动执行此操作,但我正在寻找一种使用 artisan migrate 命令的方法。

有解决办法吗?

这是我的代码:

Schema::create('companies', function($table) {

            $table->increments('id');
            $table->string('name');
            $table->integer('priority');
            $table->string('color');
            $table->string('shortname');

            $table->integer('assignation');

            $table->foreign('assignation')->references('id')->on('users');

            $table->timestamps();

        });

Schema::create('users', function($table) {

            $table->increments('id');
            $table->string('username');
            $table->string('password');
            $table->string('email');
            $table->integer('security');
            $table->string('token');

            $table->integer('company_id');

            $table->foreign('company_id')->references('id')->on('companies');

            $table->timestamps();

        });

【问题讨论】:

    标签: laravel database-schema circular-dependency


    【解决方案1】:

    你可以这样做:

    Schema::create('companies', function($table) {
    
            $table->increments('id');
            $table->string('name');
            $table->integer('priority');
            $table->string('color');
            $table->string('shortname');
    
            $table->integer('assignation');
    
            $table->timestamps();
    
        });
    
    Schema::create('users', function($table) {
    
            $table->increments('id');
            $table->string('username');
            $table->string('password');
            $table->string('email');
            $table->integer('security');
            $table->string('token');
    
            $table->integer('company_id');
    
            $table->foreign('company_id')->references('id')->on('companies');
    
            $table->timestamps();
    
        });
    
    Schema::table('companies', function($table)
        {
            $table->foreign('assignation')->references('id')->on('users');
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-13
      • 2014-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-01
      相关资源
      最近更新 更多