我有两张桌子
questions
列id(PK)
,name
。
和
answers
与columns
id(PK)
,question_id(FK)
,answer_!
,answer_2
,answer_3
,answer_4
,
我得到的数据是每个问题都有多个答案。
通过Laravel将其插入DB
的最佳方法是什么。
我试过但没有成功。
答案 0 :(得分:1)
答案 1 :(得分:1)
以下是一个示例:请注意,实际上没有对代码块进行测试。
数据库结构:
问题:id,name(问题有很多答案)
答案:id,question_id,name(答案属于问题)
我写了2个模型文件和一个Http Controller文件:
问题模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Question Extends Model
{
// Relation
public function answers()
{
return $this->hasMany(Answer::class);
}
}
答案型号:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Answer Extends Model
{
// Relation
public function question()
{
return $this->belongsTo(Question::class);
}
}
如果您想一次性保存所有问题,那么控制器(包括try-catch
es和transaction
等)可以提供帮助:
原始请求的控制器
<?php
namespace App\Http\Controllers;
use App\Question;
use Illuminate\Http\Request;
class QuestionsController Extends Controller
{
public function store(Request $request)
{
$questions = $request->input("question");
$answers = $request->input("answer");
foreach($questions as $qKey => $qName) {
$question = Question::create(["name" => $qName]);
if(array_key_exists($qKey, $answers) && is_array($answers[$qKey]))
{
foreach($answers[$qKey] as $aKey => $aName) {
if(! is_null($aName)) {
$question->answers()->create(["name" => $aName]);
}
}
}
}
}
}
对于可以更改请求参数的人来说,更好的方法是:
如果可以,请更改请求:
{
"questions": [
{
"name": "What ever",
"answers": [
{"name": "answer 1 of this question"},
{"name": "answer 2 of this question"}
]
},
{
"name": "What ever 2",
"answers": [
{"name": "answer 1 of this question"},
{"name": "answer 2 of this question"}
]
}
]
}
这将有助于你以后解析它们。
<?php
namespace App\Http\Controllers;
use App\Question;
use Illuminate\Http\Request;
class AlternateQuestionsController Extends Controller
{
public function store(Request $request)
{
foreach($request->input("questions", []) as $questionPayload) {
$question = Question::create(["name" => $questionPayload["name"]);
foreach($questionPayload["answers"] as $answerPayload) {
if(is_array($answerPayload)) {
$question->answers()->create(["name" => $answerPayload["name"]])
}
}
}
}
}
答案 2 :(得分:0)
我建议一种方式它可以帮到你。您可以创建一个中间表来保持问题和答案模型之间的关系。
<强> question_answer:强>
| answer_id | question_id |
| --------- | ----------- |
| 1 | 2 |
并检索问题的答案:
Question::find($questionId)->answer()->get();
or
Question::find($questionId)->answer;
在问题模型中添加此方法:
public function answer()
{
return $this->belongsToMany('App\Answer','question_answer','answer_id ','question_id ');
}
如果您查看此页面,您将了解更多
https://laravel.com/docs/5.3/eloquent-relationships#many-to-many