SQLSTATE [23000]:完整性约束违规:1452无法添加或更新子行:外键约束失败

时间:2016-07-01 12:45:24

标签: php laravel

为什么每次提交错误都会发生,我认为这是正确的

控制器:

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 个答案:

答案 0 :(得分: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'); 
}