问题描述
我正在与两个表建立外键关系。 父表:
Schema::create('tests',function (Blueprint $table) {
$table->bigInteger('id');
$table->timestamps();
});
和子表
Schema::create('target_sectors',function (Blueprint $table) {
$table->id();
$table->string('sector');
$table->unsignedBigInteger('tests_id');
$table->timestamps();
$table->foreign('tests_id')->references('id')->on('tests')->onDelete('cascade');
});
这是两者的模型:
use App\TargetSectors;
class Test extends Model
{
public function TargetSectors(){
return $this->hasMany(TargetSectors::class);
}
}
use App\Test;
class TargetSectors extends Model
{
public function Test()
{
return $this->belongsTo(Test::class);
}
}
在迁移或插入数据时没有给我任何错误,但是仍然没有将丝束表连接在一起,当我尝试找到与测试ID连接的目标扇区时,它返回null: enter image description here 当我尝试从父级删除一行时,它没有从子级中删除与其关联的原始文件吗? 可能是什么问题?
解决方法
我将mysql配置中的config \ database.php引擎更改为: 'engine'=>'innodb',
,在MYSQl 5.6之前,默认存储引擎为MYISAM。而且外键约束在MYISAM存储引擎中不起作用。因此数据库关系在那里不起作用。 但是在InnoDB存储引擎中,外键约束/数据库关系起作用。
只需添加$ table-> engine ='InnoDB';在所有迁移文件的表架构中。
因此代码将是:
Schema::create('tests',function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->bigInteger('id');
$table->timestamps();
});
Schema::create('target_sectors',function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->id();
$table->string('sector');
$table->unsignedBigInteger('tests_id');
$table->timestamps();
$table->foreign('tests_id')->references('id')->on('tests')->onDelete('cascade');
});