简体   繁体   中英

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

why every time on submit an error occurs, I think it is correct

Controller :

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);
}

View :

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

when submit it generates an error:

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))

You can put in a check to ensure there is a valid corresponding author.

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'); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM