![](/img/trans.png)
[英]SQLSTATE[23000]: Integrity constraint violation: 1048 Laravel 4
[英]Laravel 5: SQLSTATE[23000]: Integrity constraint violation
我有一個包含以下字段的表單:名稱,全名,描述,電子郵件,密碼,州,城市(選擇狀態時通過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不能添加或更新子行,外鍵約束失敗( yearbook
, users
,約束users_city_id_foreign
外鍵( city_id
)參考文獻cities
( id
(SQL)):插入到users
( name
, description
, email
)值(Gabriel,Description, email
gmail.com)
因此,問題與city_id是外鍵有關(表單中選項的'value'屬性是id)。 來回示例:
<option value="281">Abaíra</option>
但是,當我嘗試通過phpmyadmin插入時,它沒有任何錯誤地插入。
那么可能是什么問題呢?
這是我在控制器上的保存方法:
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
屬性
可能是因為您的city.id字段未簽名,而FK字段未簽名。 關系中使用的所有列必須完全匹配。
嘗試將代碼更改為此:
Schema::create('cities', function(Blueprint $table)
{
$table->increments('id')->unsigned();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.