我将字符串属性设置为主键,现在我想在2个表之间建立关系。我希望在另一个表中声明字符串外键,以确保这两个表已连接。但是当我要迁移表时出现错误
国家/地区
Schema::create('countries', function (Blueprint $table) {
$table->string('country_name')->unique();
$table->primary('country_name');
$table->string('country_img');
$table->timestamps();
});
目的地
Schema::create('destinations', function (Blueprint $table) {
$table->increments('dest_id');
$table->string('dest_name');
$table->integer('dest_budget');
$table->double('dest_hrs');
$table->string('dest_country')->unsigned();
$table->foreign('dest_country')->references('country_name')->on('countries');
$table->string('dest_state');
$table->string('dest_address');
$table->string('lat');
$table->string('lng');
$table->string('dest_info');
$table->string('dest_ctgr');
$table->string('dest_img');
$table->timestamps();
});
国家/地区模型
protected $primaryKey = 'country_name';
public $incrementing = false;
protected $fillable = ['country_name', 'country_img'];
public function destinasi(){
return $this->hasMany(Destination::class);
}
目的地模型
protected $primaryKey = 'dest_id';
protected $fillable = ['dest_name','dest_address','lat','lng','dest_ctgr','dest_budget','dest_hrs','dest_country','dest_state','dest_info','dest_img'];
public function country() {
return $this->belongsTo(Country::class);
}
我收到此错误:
SQLSTATE [42000]:语法错误或访问冲突:1064您有一个 SQL语法错误
我认为我编写外键的方法是错误的,并导致出现此错误。
答案 0 :(得分:2)
在“目标”模式中
替换
$table->foreign('dest_country')->references('country_name')->on('countries')
;
使用
$table->string('dest_country');
在您的模型中
public function country(){
return $this->belongsTo('App\Country', 'dest_country');
}
答案 1 :(得分:0)
仅在创建列之后才指定外键,因此您的迁移应为
Schema::create('destinations', function (Blueprint $table) {
$table->increments('dest_id');
$table->string('dest_name');
$table->integer('dest_budget');
$table->double('dest_hrs');
$table->string('dest_country');
$table->string('dest_country');
$table->string('dest_state');
$table->string('dest_address');
$table->string('lat');
$table->string('lng');
$table->string('dest_info');
$table->string('dest_ctgr');
$table->string('dest_img');
$table->timestamps();
$table->foreign('dest_country')->references('country_name')->on('countries')->onUpdate('cascade')->onDelete('cascade');;
});
推荐docs