1.添加路由 并 处理AnswerController内逻辑:
2.在question详情内页 添加提交回答的form
3.提交后由于要给Question和User模型内赋值 answer_id 所以在$fillable属性里加上'answer_id':
在处理一对多的时候
Php Laravel框架 多表关系处理 之 Eloquent一对多关系处理
Laravel One to Many Eloquent Relationship Tutorial
多对多的时候:
一对多关系,在创建answer模型的时候,需要更新user 和 question 里面的 answer_id,
但是之前忘了在migration里加外键;
【模型之间通过模型关联方法 已经默认配置了外键 讲解:一对多】
laravel模型表建立外键约束的使用:
模型:
1 //表->posts 2 class Post extends Model 3 { 4 //关联用户: 5 public function user(){ 6 //belongsTo,第一个参数:外键表,第二个:当前表的外键,第三个:外渐表的主键。 7 //如果第二个是名词+id,第三个是:id。后面的两个参数可以省略: 8 // return $this->belongsTo('App\User'); 9 return $this->belongsTo('App\User','user_id','id'); 10 } 11 } 12视图中的调用:下面的会输出:posts表中user_id对应的user表中的id的name值
1 <a href="#">{{$post->user->name}}</a></p>
现在加上,执行命令:
1 php artisan make:migration add_foreign_key_relationship_to_answers_table --table=answers
注意是answers表;
1 <?php 2 3 use Illuminate\Database\Migrations\Migration; 4 use Illuminate\Database\Schema\Blueprint; 5 use Illuminate\Support\Facades\Schema; 6 7 class AddForeignKeyRelationshipToAnswersTable extends Migration 8 { 9 /** 10 * Run the migrations. 11 * 12 * @return void 13 */ 14 public function up() 15 { 16 Schema::table('answers', function (Blueprint $table) { 17 // 18 $table->foreign('user_id')->references('id')->on('users'); 19 $table->foreign('question_id')->references('id')->on('questions'); 20 }); 21 } 22 23 /** 24 * Reverse the migrations. 25 * 26 * @return void 27 */ 28 public function down() 29 { 30 Schema::table('answers', function (Blueprint $table) { 31 // 32 $table->dropForeign('answers_user_id_foreign'); 33 $table->dropForeign('answers_question_id_foreign'); 34 }); 35 } 36 } 37 38
注意foreign key的命名:answers_user_id_foreign 查阅: Foreign Key Constraints
然后执行:
1 php artisan migrate