无法创建外键

时间:2018-07-31 07:23:31

标签: laravel-5

我想创建一个外键,它是从表“ stocks”到“ rfids”的字符串。 这两个表如下所示。 库存表:

Schema::create('stocks', function (Blueprint $table) {            

        $table->increments('tag_no');                       
        $table->string('stock_type');

        $table->string('rfid');
        $table->foreign('rfid')->references('RFID_UID')->on('rfids');

        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');

        $table->timestamps();            
    });

rfids表:

Schema::create('rfids', function (Blueprint $table) {            

        $table->increments('id');
        $table->string('RFID_UID');

        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');

        $table->timestamps();
    });

当我使用php artisan迁移时,它显示错误。

SQLSTATE [HY000]:常规错误:1005无法创建表hardware#sql-81c_c8(错误号:150“外键约束格式不正确”)(SQL:更改表{{1} }    添加约束stocks外键(stocks_rfid_foreign)引用rfidrfids))

请帮助我!

2 个答案:

答案 0 :(得分:1)

迁移顺序至关重要。您必须首先创建引用表(rfids)。

您可以通过更改文件名中的日期/时间来命令迁移。

答案 1 :(得分:0)

我以这种方式更改了表格:

Schema::create('rfids', function (Blueprint $table) {            

            $table->increments('id');
            $table->string('RFID_UID');

            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users');

            $table->timestamps();
        });

Schema::create('stocks', function (Blueprint $table) {            

        $table->increments('tag_no');                       
        $table->string('stock_type');            
        $table->string('rfid');           

        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');

        $table->timestamps();            
    });

在存储时我没有使用外键

public function store(Request $request)
    {
        //
        if(Auth::check()){
            if (Stock::where('tag_no','=',$request->input('tag_no'))->exists()) { 
                return back()->withInput()->with('errors', 'Tag number already used!');                
                }

                $rfid_tag = Rfid::where('id',"=",$request->input('tag_no'))->first();

                $stock = Stock::create([
                    'tag_no' => $request->input('tag_no'),
                    'stock_type' => $request->input('stock_type'),
                    'species' => $request->input('species'),
                    'rfid'=>$rfid_tag->RFID_UID,                                
                    'user_id' => Auth::user()->id
                ]);               

                if($stock){
                    return redirect()->route('stocks.index', ['stocks'=> $stock->tag_no])
                    ->with('success' , 'Stock created successfully');
                }                
        }        
        return back()->withInput()->with('errors', 'Error creating new Stock');        
    }

对我来说很好。但是idk是正确的解决方案。