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

Laravel关联category与semantic两张表实现编辑更新功能求助

编辑功能数据展示修复

1. 修改控制器edit方法,添加关联查询约束

按照你要求的查询逻辑,预加载semantic关联时增加table_mr = "Person"的过滤条件,修改后代码如下:

public function edit($category_id){
    $category = category::with(['semantic' => function($query){
        $query->where('table_mr', 'Person');
    }])->find($category_id);
 
    return response()->json([
        'category' => $category,
    ]);  
}

2. 修改前端AJAX回调的字段取值逻辑

semantic是category的关联子对象,需要从子对象中取对应字段,增加空值兼容避免报错,修改后代码如下:

success: function(response){     
    $('#name').val(response.category.name);
    $('#ontology').val(response.category.semantic?.semanticOntology ?? '');
    $('#seClass').val(response.category.semantic?.semantiClass ?? '');
    $('#category_id').val(category_id);        
}

semantic表更新逻辑实现

修改控制器update方法,通过关联关系获取semantic对象后更新对应字段即可,可按需选择更新逻辑,修改后代码如下:

public function update(Request $request){
    $category_id = $request->input('category_id');
    $category = category::find($category_id);
    $category->name = $request->input('name');
    $category->update();

    // 仅更新已存在的semantic关联数据
    if($semantic = $category->semantic){
        // 此处字段名请替换为你semantic表的实际字段名
        $semantic->semanticOntology = $request->input('ontology');
        $semantic->semantiClass = $request->input('seClass');
        $semantic->update();
    }

    // 若需要关联不存在时自动新增,可替换上面的更新代码为以下逻辑:
    // $category->semantic()->updateOrCreate(
    //     ['idtable_record' => $category_id, 'table_mr' => 'Person'],
    //     [
    //         'semanticOntology' => $request->input('ontology'),
    //         'semantiClass' => $request->input('seClass')
    //     ]
    // );

    return redirect()->back()->with('status', 'Updated with success');
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 09:09:03