php – Laravel 5用外键插入行
发布时间:2020-12-14 19:44:13 所属栏目:大数据 来源:网络整理
导读:我有两个表用户和帖子. 这是我的用户表迁移文件: public function up(){ Schema::create('users',function(Blueprint $table) { $table-increments('id'); $table-string('name'); $table-string('email')-unique(); $table-string('password',60); $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'); } 这是我的帖子表迁移文件 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 { $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: 解决方法
此代码创建约束,以便您的帖子必须由有效的用户ID引用. user_id字段必须包含users表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上加载了有效的用户模型,并且您已在模型上设置了“用户”和“帖子”之间的关系. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |