gpt4 book ai didi

php - 拉维尔 5 : SQLSTATE[23000]: Integrity constraint violation

转载 作者:行者123 更新时间:2023-11-29 01:39:20 27 4
gpt4 key购买 nike

我有一个包含以下字段的表单:姓名、全名、描述、电子邮件、密码、州、城市(选择州时通过 Ajax 填写)和照片(图片上传)。这是我的架构:

public function up()
{
Schema::create('states', function(Blueprint $table)
{
$table->increments('id');
$table->string('acronym');
$table->string('name');
});

Schema::create('cities', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
$table->integer('state_id')->unsigned();
$table->foreign('state_id')->references('id')->on('states');
});

Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
$table->string('fullname');
$table->string('photo');
$table->text('description');
$table->string('email');
$table->string('password', 60);
$table->integer('city_id')->unsigned();
$table->foreign('city_id')->references('id')->on('cities');
$table->rememberToken();
});
}

我的问题是,当我按下提交按钮时,会出现以下错误消息:

SQLSTATE[23000]:违反完整性约束:1452 无法添加或更新子行:外键约束失败(yearbookusers,CONSTRAINT users_city_id_foreign FOREIGN KEY (city_id) REFERENCES cities (id)) (SQL: insert into users ( name, description, email) values (Gabriel, Description, email@gmail.com))

所以问题与 city_id 作为外键有关(表单选项中的“值”属性是 id)。例如:

<option value="281">Abaíra</option>

但是当我尝试通过 phpmyadmin 插入时,它插入时没有错误。

那么可能是什么问题呢?

这是我在 Controller 上的保存方法:

public function saveRegister()
{
$rules = array(
'name' => 'required',
'description' => 'required',
'fullname' => 'required',
'email' => 'required',
'password' => 'required',
'state' => 'required',
'city' => 'required',
'photo' => 'required',
'photo' => 'image|max:3000000',
);
$val = \Validator::make(\Input::all(), $rules);

if($validar->fails()){
return redirect('register')->withErrors($val);
} else {
$user = new User(array(
'name' => \Input::get('name'),
'description' => \Input::get('description'),
'fullname' => \Input::get('fullname'),
'email' => \Input::get('email'),
'city_id' => \Input::get('city'),
));
$user->timestamps = false;
$user->save();
return redirect('register')->with('message', 'User saved!');

}
}

编辑:在 saveRegister() 方法中修复了 city_id。

最佳答案

代替

$user = new User(array(
'name' => \Input::get('name'),
'description' => \Input::get('description'),
'fullname' => \Input::get('fullname'),
'email' => \Input::get('email'),
'city' => \Input::get('city'),
));

这样做

$user = new User();
$user->fill(array(
'name' => \Input::get('name'),
'description' => \Input::get('description'),
'email' => \Input::get('email')
));
$user->fullname = \Input::get('fullname');
$user->city= \Input::get('city');

或者改变模型中的$fillable属性

关于php - 拉维尔 5 : SQLSTATE[23000]: Integrity constraint violation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30084341/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com