如何解决LARAVEL 附加或同步在服务器端无法正常工作
当我尝试在服务器端同步或附加时不起作用,这里是我的模型:
迁移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();
});
}
昆塔模型:
class Cuenta extends Model
{
use HasFactory;
protected $fillable = ['id','accountName','potencialP','potencialR'];
public function options(){
return $this->belongsToMany('App\Models\Option','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('App\Models\Cuenta','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');
});
}
我的示例代码:
$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 表上您将其创建为整数,稍后创建前键作为字符串
在此处查看条件和限制以了解外键https://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html
可能在本地您正在使用 SQLITE,它几乎在所有情况下都不会验证前键,请尝试在本地创建一个 mysql 环境以处理相同的方面
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。