一般错误:1005 无法创建表 `chatbot`.`staistic_students`(错误号:150“外键约束的格式不正确”)

时间:2021-07-09 10:53:09

标签: laravel migration

当我在laravel项目中进行迁移时,它抛出这样一个错误:Can't create table chatbot.staistic_students (errno: 150 "Foreign key constraint is wronglyformed") (SQL: alter表staistic_students添加约束staistic_students_right_answers_stu_foreign外键(right_answers_stu)引用user_right_answers(id))

这是我的迁移

public function up()
    {
        Schema::create('staistic_students', function (Blueprint $table) {
            $table->id('chapters_id');
            $table->foreignId('user_id')->constrained();
            $table->decimal('correct_rate_stu');
            $table->foreignId('right_answers_stu')->constrained('user_right_answers');
            $table->foreignId('wrong_answers_stu')->constrained('user_wrong_answers');
        });
    }

那是我的桌子

class StatisticStudent extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'user_id','chapters_id','correct_rate_stu','right_answers_stu','wrong_answers_stu'
    ]; 
    use HasFactory;
    public $timestamps = false;
}
class UserRightAnswer extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'id','user_id','answers_id','chapters_id','right_answers_stu'
    ]; 
    use HasFactory;
    public $timestamps = false;
}
class UserWrongAnswer extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'id','user_id','answers_id','chapters_id','wrong_answers_stu'
    ]; 
    use HasFactory;
    public $timestamps = false;
}

表 statistic_students 基于表 user_right_answers 表 user_wrong_answers

而且我认为这个名字是正确的,但是它不起作用总是抛出一个错误:外键约束不正确

有人可以帮忙吗?

这是从另一个表迁移

public function up()
    {
        Schema::create('user_right_answers', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained('user_answers');
            $table->foreignId('answers_id')->constrained('user_answers');
            $table->foreignId('chapters_id')->constrained('questions');
            $table->integer('right_answer_stu');
        });
    }

public function up()
    {
        Schema::create('user_wrong_answers', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained('user_answers');
            $table->foreignId('answers_id')->constrained('user_answers');
            $table->foreignId('chapters_id')->constrained('questions');
            $table->integer('wrong_answer_stu');
        });
    }

0 个答案:

没有答案