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

Laravel结合Ajax无法通过关联模型获取数据求助

Laravel Ajax关联模型数据无法加载到模态框的问题修复

我是Laravel的Ajax新手,希望使用Laravel的Eagerload功能从关联模型获取数据到Blade模态框中。尝试了各种方法但都无效,希望通过Expenses模型的emp_id外键获取User模型中的用户名,请问哪里遗漏了?


现有代码

User模型(原标注为Expenses Model)

protected $fillable = [
    'name',
    'surname',
    'email',
    'password',
    'status',
    'role',
];

protected $hidden = [
    'password',
    'remember_token',
];

public function Expense () {
    return $this->hasMany(ExpensesModel::class);
}

Expenses模型

use HasFactory;

protected $table = 'expenses'; 

protected $fillable = [
    'id',
    'emp_id',
    'expense_input_date',
    'expense_type',
    'expense_category',
    'reason',
    'status'
];

public function UserExpense () {
    return $this->belongsTo(User::class, 'emp_id');
} 

控制器代码

public function edit (Request $request) {
    $req_id = array('id' => $request->id);
    
    if($request->ajax()) { 
        $employee  = ExpensesModel::with('UserExpense')->where('id' ,$req_id)->first();
        return response()->json($employee);
    }
} 

Blade脚本

function editFunc(id){
    $.ajax({
    type:"POST",
    url: "{{ url('/expenses/advancedtable/edit') }}",
    data: { id: id },
    dataType: 'json',
    success: function(res){
        $('#EmployeeModal').html("Edit Employee");
        $('#employee-modal').modal('show');
        $('#id').val(res.id);   
        $('#emp_id').val(res.name);
        $('#expense_input_date').val(res.expense_input_date);
        $('#expense_type').val(res.expense_type); 
        $('#expense_category').val(res.expense_category);
        $('#expense_slip_no').val(res.expense_slip_no);
        $('#expense_amount').val(res.expense_amount);
        $('#currency').val(res.currency);
        $('#description').val(res.description);
    }
    });
}  

错误点分析及修复

1. 控制器查询条件错误

$req_id = array('id' => $request->id); 属于冗余代码,且where('id', $req_id)会将数组作为查询值,导致SQL语法错误。直接使用$request->id或find()方法即可:

修改后的控制器代码:

public function edit(Request $request) {
    if($request->ajax()) { 
        // 直接通过ID查询并预加载关联模型
        $employee = ExpensesModel::with('UserExpense')->find($request->id);
        return response()->json($employee);
    }
}

2. Ajax请求缺少CSRF令牌

Laravel默认拦截无CSRF令牌的POST请求,需在请求数据中添加_token字段:

修改后的Blade脚本:

function editFunc(id){
    $.ajax({
        type:"POST",
        url: "{{ url('/expenses/advancedtable/edit') }}",
        data: { 
            id: id,
            _token: "{{ csrf_token() }}" // 新增CSRF令牌
        },
        dataType: 'json',
        success: function(res){
            $('#EmployeeModal').html("Edit Employee");
            $('#employee-modal').modal('show');
            $('#id').val(res.id);   
            // 从关联模型中获取用户名,注意键名为userExpense(Laravel自动转小驼峰)
            $('#emp_id').val(res.userExpense.name);
            $('#expense_input_date').val(res.expense_input_date);
            $('#expense_type').val(res.expense_type); 
            $('#expense_category').val(res.expense_category);
            $('#expense_slip_no').val(res.expense_slip_no);
            $('#expense_amount').val(res.expense_amount);
            $('#currency').val(res.currency);
            $('#description').val(res.description);
        }
    });
}

3. 关联模型数据获取错误

之前直接使用res.name是错误的,name字段属于关联的User模型,预加载的关联数据会放在userExpense字段下(Laravel会将模型中定义的关联方法名UserExpense转为小驼峰userExpense),正确的获取方式是res.userExpense.name。

4. (可选)规范关联方法命名

Laravel推荐关联方法名使用小写开头的驼峰命名,更符合框架约定:

修改Expenses模型的关联方法:

// 将UserExpense改为userExpense
public function userExpense() {
    return $this->belongsTo(User::class, 'emp_id');
}

对应的控制器查询需同步修改:

$employee = ExpensesModel::with('userExpense')->find($request->id);

验证步骤

  1. 打开浏览器开发者工具,查看Ajax请求的响应内容,确认返回的JSON中包含userExpense字段及对应的用户信息。
  2. 检查控制台是否有CSRF相关错误,确保_token字段正确传递。

内容的提问来源于stack exchange,提问作者Serkan Taçkıran

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 21:54:15