我想创建一个外键,它是从表"stocks“到"rfids”的字符串。这两个表如下所示。stocks表:
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 migrate时,它显示错误。
SQLSTATEHY000:一般错误: 1005无法创建表hardware。#sql-81c_c8(错误号: 150“外键约束的格式不正确”) (SQL: alter table stocks add constraint stocks_rfid_foreign foreign key (rfid) references rfids (RFID_UID))
谁来帮帮我!
发布于 2018-07-31 15:51:38
我这样修改了表:
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');
}它对我来说很好。但如果这是正确的解决方案,请注意。
发布于 2018-08-04 23:09:59
迁移顺序至关重要。您必须首先创建被引用的表(rfids)。
您可以通过更改文件名中的日期/时间来排序迁移。
https://stackoverflow.com/questions/51607643
复制相似问题