繁体   English   中英

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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