我有两个表 Users 和 Posts。 这是我的用户表迁移文件:
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');
}
这是我的帖子表迁移文件
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 扩展 Controller { 公共(public)函数存储(请求 $request) {
$validator = Validator::make($request->all(),Post::$rules);
if($validator->passes()){
$post = new Post();
$post->title = $request->get('title');
$post->body = $request->get('body');
$post->user_id = $request->get('id');
$post->slug = Slug::generateSlug($request->get('title'));
$post->save();
return Redirect::route('admin.posts.index');
}
else{
return Redirect::route('admin.posts.create')->withErrors($validator)->withInput();
}
}
每次我插入一个新帖子,我总是看到以下错误
"Connection.php 第 614 行中的 QueryException:
SQLSTATE [23000]:违反完整性约束:1452 无法添加或更新子行:外键约束失败('blog'。'posts',CONSTRAINT 'posts_user_id_foreign' FOREIGN KEY('user_id')REFERENCES 'users'('id ') 在更新级联上删除级联)
"
我想知道我做错了什么。
最佳答案
此代码创建一个约束,以便您的帖子必须由有效的用户 ID 引用。 user_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
var 上加载了一个有效的用户模型,并且您已经在模型上设置了用户和帖子之间的关系。
关于php - Laravel 5 使用外键插入行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28858067/