You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

前端传含Questions数组的测试数据,后端存储后无法获取问题数据

问题描述

我有一个前端函数,负责将Title(字符串)、Description(字符串)和Questions(数组)存入数据库,但解析返回数据时,只能拿到标题和描述信息。通过浏览器开发者工具的Network面板能看到Questions数组已经在请求Payload里,但响应预览、返回结果里都没有这个数组,alert弹窗输出的JSON数据也只显示标题、描述、创建时间和更新时间。我已经给Questions创建了独立的Model、Controller和数据表,但问题还是没解决,请问我漏了什么环节?


前端保存函数

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

问题原因及解决方法

1. 存储接口返回时未加载关联的Questions

你在storeData方法中创建完关联的Question后,直接返回了$test对象,但Laravel模型默认不会自动加载关联数据。需要在返回前手动加载关联:

// 在返回前加载关联的questions
$test->load('questions');
return response()->json(['message' => 'Test created successfully', 'test' => $test], 201);

2. 获取Tests的接口未预加载关联数据

getTests方法里的Test::all()只会获取Test表的基础数据,不会自动查询关联的Questions表。需要用with方法预加载关联:

public function getTests(): \Illuminate\Http\JsonResponse
{
    // 预加载questions关联
    $tests = Test::with('questions')->get();
    return response()->json($tests);
}

3. 确认Test模型的关联关系是否正确

必须确保Test模型中已正确定义与Question的关联:

// Test.php模型文件
public function questions()
{
    return $this->hasMany(Question::class);
}

同时建议在Question模型中定义反向关联:

// Question.php模型文件
public function test()
{
    return $this->belongsTo(Test::class);
}

内容的提问来源于stack exchange,提问作者TraktorJack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 03:29:54