1. Add the routing and processing logic AnswerController:
form 2. Answer in the question submitted details Add Page
3. Since the submission within give the Question and User model assignment answer_id so $ fillable property in plus 'answer_id':
In dealing with many of
Laravel One to Many Eloquent Relationship Tutorial
Many-time:
To-many relationship, when creating the model answer, and the question needs to be updated user inside answer_id,
However, before the migration Riga forget foreign key;
[Between model through the model associated with the default configuration approach has been to explain the foreign key: many ]
laravel model table to establish a foreign key constraint use:
model:
1 // Table -> Posts 2 class the extends the Model Post . 3 { . 4 // associated with the user: . 5 public function User () { . 6 // a belongsTo, the first parameter: foreign key table, a second: the current foreign key table third: an outer tapered table's primary key. 7 // If the second is a noun + id, and the third is: id. The last two parameters can be omitted: . 8 // return $ this-> a belongsTo ( 'the App \ the User'); . 9 return $ this-> a belongsTo ( 'the App \ the User', 'user_id', 'ID'); 10 } 11 } 12Call view: the following outputs: Posts user_id id table name corresponding to the value of the user table
1 <a href="#">{{$post->user->name}}</a></p>
Now add, execute the command:
1 php artisan make:migration add_foreign_key_relationship_to_answers_table --table=answers
Note that answers the table;
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
Note that foreign key name: answers_user_id_foreign review: Foreign Key the Constraints
Then execute:
1 php artisan migrate