我有一个简单的文章模型和一个用户模型.
Article "belongsTo" a User and a User "hasMany" Article.
Therefore my article migration has a foreign key called "user_id".
Schema::create('articles', function(Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('body');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
然而,每当我在一个隐藏字段中传递"user_id"时,我就会收到一条错误消息.
{!! Form::open(array('route' => 'articles.store')) !!}
{!! Form::hidden('userId', $user->id) !!}
<div class="form-group">
{!! Form::label('title', 'Title') !!}
{!! Form::text('title', null, array('class' => 'form-control')) !!}
</div>
<div class="form-group">
{!! Form::label('text', 'Write your Article') !!}
{!! Form::textarea('text', null, array('class' => 'form-control')) !!}
</div>
{!! Form::submit('Create Article', array('class' => 'btn btn-default btn-success')) !!}
{!! Form::close() !!}
This is the error message. And I understand that I doesn't try to insert the value for the 'user_id' into the articles table.
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (
tags
.articles
, CONSTRAINTarticles_user_id_foreign
FOREIGN KEY (user_id
) REFERENCESusers
(id
)) (SQL: insert intoarticles
(title
,body
,updated_at
,created_at
) values (Title, Some text, 2015-03-21 23:19:33, 2015-03-21 23:19:33))
Here is my Store Method on my AriclesController:
Article::create([
'title' => Input::get('title'),
'body' => Input::get('text'),
'user_id' => Input::get('userId')
]);
return Redirect::to('articles');
还有几十个类似标题的开放式Stackoverflow问题,我正在寻找适合我的具体情况的答案,但没有成功,因此我提前向您表示感谢.
How do I save an article into my database?