【问题标题】:How to set the primary key itself as a foreign key in laravel?如何在laravel中将主键本身设置为外键?
【发布时间】:2022-01-12 15:35:50
【问题描述】:

这听起来很无聊,但我想知道我是否可以让主键在 Laravel 中作为外键工作,而且我是 Laravel 的新手。

所以,我有两个迁移“用户”和“学生”,如下所示: 用户

 Schema::create('users', function (Blueprint $table) {
            $table->string('uniqueId', 30)->primary();
            $table->text('password');
            $table->string('userType');
            $table->timestamps();
        });

学生

Schema::create('students', function (Blueprint $table) {
            $table->string('uniqueId', 30)->primary();
            $table->text('name');
            $table->text('fName');
            $table->text('mName');
            $table->text('addr');
            $table->string('image');
            $table->integer('class');
            $table->integer('roll');
            $table->string('year');
            $table->timestamps();
        });

所以,我想要的只是 Student (uniqueId) 中的主键也可以作为引用 User 表中的“uniqueId”列的外键。

提前致谢。

【问题讨论】:

    标签: php laravel laravel-5 eloquent


    【解决方案1】:

    这不是您对迁移文件所做的事情,而是您如何在模型本身中设置关系,老实说,我会尝试避免使用相同的主键来表示两个模型,而是添加另一个模型列到名为 $table->string('user_id', 30)->index(); 的学生表中,然后在模型类中创建该关系,如下所示:

        public function user()
        {
            return $this->hasOne(User::class);
        }
    
    

    【讨论】:

      【解决方案2】:

      虽然没有必要,但您可以通过迁移添加外键约束。

      https://laravel.com/docs/8.x/migrations#foreign-key-constraints

      【讨论】:

        【解决方案3】:

        你可以这样做:

        if (!Schema::hasTable('users')) {
            Schema::create('users', function (Blueprint $table) {
                $table->increments('id');
                $table->text('password');
                $table->string('userType');
                $table->timestamps();
            });
        }
        
        if (!Schema::hasTable('students')) {
            Schema::create('students', function (Blueprint $table) {
                $table->increments('id');
                $table->text('name');
                $table->text('fName');
                $table->text('mName');
                $table->text('addr');
                $table->string('image');
                $table->integer('class');
                $table->integer('roll');
                $table->string('year');
                $table->timestamps();
                $table->foreign('user_id', 'fk_users_user_id')
                    ->references('id')->on('users')->onUpdate('NO ACTION')->onDelete('cascade');
                });
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-07-08
          • 2021-12-02
          • 2017-05-31
          • 1970-01-01
          • 2017-07-15
          • 2023-04-11
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多