【发布时间】:2018-09-21 17:26:37
【问题描述】:
我无法理解如何将 arra 作为 JSON 字符串保存到我的数据库中。我已经尝试了一些我看到的教程,但似乎没有一个是一个好的解决方案。我希望将答案一起保存到一个表格行中。当我 dd 我的代码时,它显示了一个 arrey 中的所有 asnwers,但我无法保存它:
数组到字符串的转换(SQL:insert into
answers(user_id,template_id,answer) 值 (3, 1, AOJf3lEibJCqqbdGH2ha86EKgvgP1QrijQmQ8Btp))"
这是我的代码。商店控制器:
public function store(Request $request, Template $template, Question $question, Answer $answer)
{
$answers = new Answer;
$answers->user_id = auth()->user()->id; //currently logged in user
$answers->template_id = $template->id; //currently use template
$answers->answer = $request->all();
// dd($answers);
$answers->save();
return back()->with('success', 'Your Answers were Successfully Created into a note');
}
查看:
@foreach ($questions as $question) <!-- Index counts the questions shown -->
{!! Form::open(['action' => ['AnswersController@store', $template->id], 'method' => 'POST']) !!}
<div class="panel panel-default">
<div class="panel-body">
<p class="pull-left question2"> {{$question->question}}</p>
<div class="form-group answer">
{{Form::label('', '')}}
{{Form::text('answer[]', null, array('class'=>'form-control', 'placeholder' => 'Type in your answer'))}}
{{-- {{Form::hidden('question[]', $question->question, null, array('class'=>'form-control'))}} --}}
</div>
</div>
</div>
@endforeach
{{Form::submit('Save', ['class'=>'btn btn-primary'])}}
{!! Form::close() !!}
<hr>
我的数据库条目:
public function up()
{
Schema::create('answers', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->nullable();
$table->foreign('user_id')->references('id')->on('templates')->onDelete('cascade');
$table->integer('template_id')->unsigned()->nullable();
$table->foreign('template_id')->references('id')->on('templates')->onDelete('cascade');
$table->string('answer');
});
}
我也不确定表中的答案是否应该设置为字符串。 任何帮助,将不胜感激!谢谢。
【问题讨论】:
-
$table->string('answer');应该是 $table->json('answer'); $answers->answer = json_encode($request->all());在模型保护 $casts = ['answers'=> 'array']; laravel.com/docs/5.6/eloquent-mutators#attribute-casting