提问人:TraktorJack 提问时间:11/17/2023 最后编辑:ShadowTraktorJack 更新时间:11/18/2023 访问量:51
您可以将一系列问题与两个字符串一起保存到 mySQL 中吗?
Can you save an array of questions to mySQL along with two strings?
问:
我有一个函数将 Title(string)、Description(string) 和 Questions(array) 传递到我的数据库。但是,当我解析数据时,我只收到标题和描述。我尝试了各种将数据保存到 questions 数组的方法,但是使用检查器工具(特别是“网络”选项卡),我可以看到 Questions 数组是 Payload 的一部分。这是否意味着我错误地保存了数据,或者我解析错误了数据?这是保存功能:
const saveTest = () => {
const updatedTestData = {
title: testData.title,
description: testData.description,
questions: testData.questions.map(question => ({
text: question.text,
type: 'text',
id: question.id,
})),
};
axios.post('/api/tests', updatedTestData)
.then(response => {
console.log(response.data.message);
alert("Test Saved! " + JSON.stringify(response.data));
})
.catch(error => {
console.error('Error saving test:', error);
});
}
以下是解析:
useEffect(() => {
if (selectedTeaserTitle) {
axios.get('/api/tests/all')
.then((response) => {
const filteredData = response.data.filter(test => test.title === selectedTeaserTitle);
setData(filteredData);
console.log(filteredData);
})
.catch(error => {
console.error('Error fetching tests:', error);
});
}
}, [selectedTeaserTitle]);
这是我的TestController:
class TestController extends Controller
{
public function storeData(Request $request): \Illuminate\Http\JsonResponse
{
$validatedData = $request->validate([
'title' => 'required',
'description' => 'required',
'questions' => 'array', // Validate that 'questions' is an array
]);
$test = Test::createTest($validatedData);
// Check if 'questions' data is present in the request
if ($request->has('questions')) {
$questions = $request->input('questions');
// Store the questions data related to the test
foreach ($questions as $questionData) {
// Create a new question and associate it with the test
$question = new Question(['text' => $questionData['text']]);
$test->questions()->save($question);
}
}
return response()->json(['message' => 'Test created successfully', 'test' => $test], 201);
}
public function getTests(): \Illuminate\Http\JsonResponse
{
// Retrieve data from the 'tests' table
$tests = Test::all(); // This fetches all test records from the database. Only need one at a time tho
return response()->json($tests);
}
}
我可以看到这些问题是有效负载的一部分,但它们在“预览”或“响应”选项卡中不可见。我的也只显示标题、描述、创建日期和更新日期。我甚至为问题数组创建了单独的模型、控制器和表格,但在我看来,这不应该那么困难。我错过了什么?alert(JSON.stringify())
答:
0赞
Denis Sinyukov
11/18/2023
#1
您需要调试到服务器,我认为服务器上的问题出在测试和问题创建本身
public function storeData(Request $request): \Illuminate\Http\JsonResponse
{
$validatedData = $request->validate([
'title' => 'required',
'description' => 'required',
'questions' => 'array',
'questions.*.text' => 'required|string',
'questions.*.type' => 'required|string',
'questions.*.id' => 'required|integer',
]);
$test = Test::createTest(
Arr::only($validatedData, ['title', 'description'])
);
// Check if 'questions' data is present in the request
$questions = $request->get('questions', []);
if (count($questions)) {
$test->questions()->createMany(array_column($questions, 'text'));
// OR save many
$questions = array_map(function ($text) {
return new Question(['text' => $text]);
}, array_column($questions, 'text');
$test->questions()->saveMany($questions);
}
return response()->json(['message' => 'Test created successfully', 'test' => $test->load('questions')], 201);
}
评论
'/api/tests'