[英]Laravel 5.1 eloquent relations
我正在使用Laravel 5.1實施測驗系統
我在問題表中插入和更新數據時遇到一些問題
MySQL架構
Subjects (Table 1)
________________
Subject_ID (Primary Key) auto_increment,
Subject_Name
Questions (Table 2)
________________
Question_ID (Primary Key) auto_increment,
Question,
Options_1,
Options_2,
Options_3,
Options_4,
Answer,
Subject_Id (Foreign Key refers to Primary Key of Subjects Table [Table 1])
在問題表中插入問題時,我無法從“主題”表中獲取Subject_Id
我正在使用Laravel實現以下查詢
insert into questions values("", "Question", "Option 1", "Option 2", "Option 3", "Option 4", "Answer", "select subject_id from subjects where subject_name = $subject_name");
$ subject_name是從用戶界面獲取主題名稱的變量
您可以使用遷移文件創建這兩個表。
命令行中的第一個寫命令
php artisan make:migration Subjects
因此,創建遷移文件並用於第二個表
php artisan make:migration Questions
之后,進入您的應用程序目錄/數據庫/遷移,在那里您將找到這2個遷移文件。 在方法up()的第一個文件“ Subjects”中,您需要此代碼
Schema::create('Subjects', function (Blueprint $table) {
$table->increments('Subject_ID');
$table->string('Subject_Name',255);
$table->timestamps();
});
在方法up()的第二個文件“問題”中,您需要此代碼
Schema::create('Questions', function (Blueprint $table) {
$table->increments('Question_ID');
$table->string('Question',255);
$table->string('Options_1',255);
$table->string('Options_2',255);
$table->string('Options_3',255);
$table->string('Options_4',255);
$table->string('Answer',255);
$table->integer('Subject_Id')->unsigned();
$table->foreign('Subject_Id')->references('Subject_ID')->on('Subjects');
$table->timestamps();
});
在所有文件都在服務器上之后,再次轉到命令行並寫入
php artisan migrate
我希望我能幫助你。 如果我不了解您,並且如果您不想這樣做,請寫評論。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.