问题描述
我有一个简单的文章模型和一个用户模型.
I have a simple Article Model and a User Model.
文章属于"用户和用户有很多"文章.
Article "belongsTo" a User and a User "hasMany" Article.
因此,我的文章迁移具有一个名为"user_id"的外键.
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"的文章时,都会收到错误消息.
Yet whenever I create an Article where I pass the "user_id" in a hidden field I get an error message.
{!! 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() !!}
这是错误消息.而且我知道我不会尝试将'user_id'的值插入商品表中.
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.
这是我的AriclesController上的存储方法:
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问题,但我仍在搜索适合我具体情况的答案,但仍未成功,因此,我非常感谢陌生人.
There are dozens of other open Stackoverflow Questions with a similar title, and I am searching yet unsuccessfully for the answer that fits my specific case, therefore I thank you in advance kind stranger.
如何将文章保存到数据库中?
How do I save an article into my database?
推荐答案
确保您的Article模型的fillable
属性中具有user_id
.
Make sure you have user_id
in the fillable
property of your Article model.
http://laravel.com/docs/5.0/eloquent#mass-assignment
这篇关于Laravel 5:违反完整性约束:1452无法添加或更新子行:外键约束失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!