您可以将一系列问题与两个字符串一起保存到 mySQL 中吗?

Can you save an array of questions to mySQL along with two strings?

提问人:TraktorJack 提问时间:11/17/2023 最后编辑:ShadowTraktorJack 更新时间:11/18/2023 访问量:51

问:

我有一个函数将 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())

JavaScript MySQL 公理

评论

0赞 David 11/17/2023
澄清一下...您是否表示已确认请求包含您期望的数据,但来自该 URL 的结果响应不包含您期望的数据?'/api/tests'
0赞 TraktorJack 11/17/2023
这就是我的理解,是的
1赞 David 11/17/2023
在这种情况下,听起来您需要检查和调试服务器端代码。所示代码中没有任何内容与数据库交互。
0赞 TraktorJack 11/17/2023
就像在我的 TestController 中一样?对不起,我是数据库等的新手,我不太确定您需要哪些信息
0赞 David 11/17/2023
好吧,如果问题是写入数据库或从数据库读取的代码没有按照您的预期执行操作,那么您需要检查和调试写入数据库或从数据库读取的代码。或者,如果问题是接收和响应 AJAX 请求的代码没有执行预期的操作,则需要检查和调试接收和响应 AJAX 请求的代码。从您的描述来看,问题中显示的代码似乎没有任何失败,而是其他地方的其他代码失败了。除非您能另行澄清。

答:

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);
}