Php Laravel 5使用外键插入行
我有两张表,用户和帖子。 这是我的用户表迁移文件:Php Laravel 5使用外键插入行,php,mysql,laravel-5,Php,Mysql,Laravel 5,我有两张表,用户和帖子。 这是我的用户表迁移文件: public function up() { Schema::create('users', function(Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->
public function up()
{
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->string('password_temp',60);
$table->integer('active');
$table->string('code',60);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('users');
}
这是我的posts表迁移文件
public function up()
{
Schema::create('posts', function(Blueprint $table){
$table->increments('id');
$table->string('title');
$table->text('body');
$table->integer('user_id')->unsigned();
$table->string('slug');
$table->timestamps();
});
Schema::table('posts',function(Blueprint $table){
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade')
->onUpdate('cascade');
});
}
AdminPostsController扩展控制器{
公共函数存储(请求$Request)
{
}
每次我插入一篇新文章,我总是看到以下错误
“QueryException in Connection.php第614行:
SQLSTATE[23000]:完整性约束冲突:1452无法添加或更新子行:外键约束失败('blog''posts',约束'posts'u user\u id\u foreign'外键('user\u id')在更新级联上的删除级联上引用'users'('id')
”
我想知道我做错了什么。此代码创建了一个约束,因此您的帖子必须由有效的用户id引用。
用户id
字段必须包含用户表id字段上的现有键
$table->foreign('user_id')
->references('id')
->on('users')
在保存新帖子之前,请尝试关联用户
$post = new Post();
$post->title = $request->get('title');
$post->body = $request->get('body');
$post->user()->associate($user);
$post->save();
假设您在
$user
变量上加载了一个有效的用户模型,并且在模型上设置了用户和帖子之间的关系。听起来好像您没有使用有效的用户id
插入帖子。您能告诉我们如何创建新帖子吗?我刚刚添加了store函数@lukasgeiterInstead of setting>用户id
和slug
在$post
上你在$request
上这样做谢谢,我刚刚编辑了这个函数,但是我仍然得到了相同的结果@lukasgeiterIs$request->get('id')
甚至设置了?dodd($request->get('id')
来检查我是否做了更改。我想问题是$request->get('id'))
$post = new Post();
$post->title = $request->get('title');
$post->body = $request->get('body');
$post->user()->associate($user);
$post->save();