当我试图在服务器端同步或连接时不起作用,这里是我的模型:
迁移Cuenta:
public function up()
{
Schema::create('cuentas', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->id();
$table->string('accountName');
$table->integer('potencialP');
$table->integer('potencialR');
$table->timestamps();
});
}
Cuenta模型:
class Cuenta extends Model
{
use HasFactory;
protected $fillable = ['id','accountName','potencialP','potencialR'];
public function options(){
return $this->belongsToMany('AppModelsOption','cuentas_options');
}
}
迁移选项:
public function up() {
Schema::create('options', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->id();
$table->string('titulo');
$table->integer('puntos');
$table->unsignedBigInteger('field_id');
$table->timestamps();
$table->foreign('field_id')->references('id')->on('fields');
});
}
选项型号:
class Option extends Model
{
use HasFactory;
protected $fillable = ['id'];
public function cuentas(){
return $this->belongsToMany('AppModelsCuenta','cuentas_options');
}
}
Cuentas_option迁移:
public function up()
{
Schema::create('cuentas_options', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->id();
$table->string('cuenta_id');
$table->unsignedBigInteger('option_id');
// $table->timestamps();
$table->foreign('cuenta_id')->references('id')->on('cuentas');
$table->foreign('option_id')->references('id')->on('options');
});
}
MyExampleCode:
$cuenta = Cuenta::find('8963596291');
$option = Option::all()->pluck('id');
$cuenta->options()->sync($option);
return $cuenta;
它返回:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`potencial_pr`.`cuentas_options`, CONSTRAINT `cuentas_options_cuenta_id_foreign` FOREIGN KEY (`cuenta_id`) REFERENCES `cuentas` (`id`)) (SQL: insert into `cuentas_options` (`cuenta_id`, `option_id`) values (8963596291, 1))
在我的本地服务器正常工作,但不在服务器托管,有人能帮我吗?
编辑:IM使用LARAVEL 8,并更新了CUENTAS_OPTIONS迁移:
public function up()
{
Schema::create('cuentas_options', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->id();
$table->unsignedBigInteger('cuenta_id');
$table->unsignedBigInteger('option_id');
// $table->timestamps();
$table->foreign('cuenta_id')->references('id')->on('cuentas');
$table->foreign('option_id')->references('id')->on('options');
});
}
问题还在继续,IM在本地主机上使用10.4.11-MariaDB-MariaDB.org二进制分发,在服务器上使用5.6.49-cll-lve-MySQL社区服务器(GPL(,这可能是问题吗?
我通过在CUENTAS模型上添加KEYTYPE和AUTO_INCREMENT=FALSE 来解决这个问题
问题可能出现在$table->string('cuenta_id');
,因为在cuentas
表上,您将列创建为ID,这取决于您的laravel版本,它可能是unsigned integer
或unsigned big integer
要使外键正常工作,您必须确保相关列的类型完全相同,具有相同的字符集和所有内容,在您的情况下,在cuentas表上,您将其创建为整数,稍后o将外键创建为字符串
有关外键,请参阅条件和限制https://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html
可能在本地使用的SQLITE几乎在所有情况下都不会验证外键,请尝试在本地创建一个mysql环境来使用相同的方面