2016-07-01 82 views
1

爲什麼提交發生錯誤,我認爲這是正確的每次SQLSTATE [23000]:完整性約束違規:1452不能添加或更新子行,外鍵約束失敗

控制器:

public function create() 
{ 
    $author1['tambah_author'] = \DB::table('authors')->lists('username','id'); 
    $author1['id_author'] = \DB::table('authors')->lists('id'); 

    return View::make('article.add',$author1)->with('authors',$author1); 
} 

查看:

{{ Form::select('author', 
       array_merge(['' => 'Pilih Author'], $tambah_author), 
       $id_author, 
       array('class'=>'form-control')) }} 

時提交生成錯誤:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`laravel`.`articles`, CONSTRAINT `articles_ibfk_1` FOREIGN KEY (`author_id`) REFERENCES `authors` (`id`) ON DELETE CASCADE) (SQL: insert into `articles` (`judul`, `body`, `author_id`, `updated_at`, `created_at`) values (sadsadd, sadas, 2, 2016-07-01 12:44:54, 2016-07-01 12:44:54)) 
+1

是否有ID爲2的作者嗎?代碼插入數據庫的位置在哪裏? –

+0

公共職能店() \t { \t \t $文章=新的第(); \t \t $ article-> judul = Input :: get('judul'); \t \t $ article-> body = Input :: get('isi'); \t \t $ article-> author_id = Input :: get('author'); \t \t $ article-> save(); \t \t回重定向到::( '文章'); \t} – rojib

回答

0

您可以進行檢查以確保存在有效的通信作者。

public function store() { 
    $article = new Article(); 
    $article->judul = Input::get('judul'); 
    $article->body = Input::get('isi'); 
    $article->author_id = Author::find(Input::get('author'))->id; 
    if (!$article->author_id) throw new Exception('not a valid author.'); 
    $article->save(); 
    return Redirect::to('article'); 
} 
+0

不能,錯誤:試圖在獲得非對象 – rojib

+0

的屬性'$物品─> AUTHOR_ID =作者::發現(輸入::獲得( '作者')) - > ID;'? –

+0

它一樣,不能 – rojib

相關問題