【发布时间】:2017-03-20 14:24:49
【问题描述】:
我是laravel的新手。我需要将表单字段一个保存在一个表中,另一个保存在laravel的另一个表中。这两个表具有外键引用。在一个表中保存了数据,但另一个无法保存数据库。任何人都可以为此提出建议吗?
提前谢谢
表格问题: ID, 考试编号, 问题
表答案: ID, question_id, 选项, 答案
模型 1:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Question extends Model
{
protected $table='question';
public function answer()
{
return $this->hasMany('Answer');
}
}
模型 2:
<?php
namespace App;
namespace App\Http\Controllers;
use Illuminate\Database\Eloquent\Model;
class Answer extends Model
{
protected $table='answer';
public function question()
{
return $this->BelongsTo('Question');
}
}
添加问题页面
public function add_question()
{
$exam =DB::table('exam')->select(array('id', 'exam_name'))->get();
return view('add_question')->with('exam',$exam);
}
//it shows the form page
验证问题和答案详情并将其保存到数据库中
public function validate_question()
{
$rules = array(
'question'=>'required|max:300'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
return edirect::back()->withErrors($validator,'login')->withInput(Input::except('question'));
}
else
{
$question =new Question;
$question->exam_id = Input::get('exam_id');
$question->question = Input::get('question');
$question->save();
if($question->save()){
$answer =new Answer;
$answer ->options = Input::get('options');
$answer ->answers = Input::get('answers');
$question->answer()->save($answer);
}
}
Session::flash('message', 'Successfully created question record!');
return Redirect::to('question');
}
我有错误:
HomeController.php 第 261 行中的 FatalErrorException:找不到类“App\Answer”。
请任何人对此提出建议
【问题讨论】:
-
你已经尝试了什么?
-
提供你的存在代码来解决你的问题!!
-
感谢您的回复 Mr.Amit 和 Mr.Rimon。我包含了我的代码。我犯了什么错误。请您给我建议
标签: database forms laravel laravel-5.2