SQLSTATE[23000]:完整性约束违反:1452不能添加或更新子行:外键约束失败


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

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

控制器:

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

您可以检查是否有有效的通信作者。

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