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

Laravel+Vue.js+Inertia表格排序重复代码重构求助

重构Laravel查询代码消除重复

可以利用Laravel查询构造器的when()方法简化逻辑,抽离重复的查询代码,仅在满足条件时添加排序子句,无需拆分两个独立代码块:

基础重构版本

$company = Company::query()
    ->orWhere('code', 'LIKE', '%' . request('search') . '%')
    ->orWhere('description', 'LIKE', '%' . request('search') . '%')
    ->orWhere('email', 'LIKE', '%' . request('search') . '%')
    // 仅当请求同时包含field和direction参数时,添加排序逻辑
    ->when(request()->has(['field', 'direction']), function ($query) {
        $query->orderBy(request('field'), request('direction'));
    })
    ->with(['user' => function ($query) {
        $query->select('id', 'name', 'email');
    }])
    ->paginate(5);

进阶优化版本(更安全健壮)

实际开发中建议补充参数验证和逻辑优化,规避潜在问题:

// 验证排序参数合法性,防止非法字段/方向引发错误
$sortField = in_array(request('field'), ['code', 'description', 'email', 'created_at']) ? request('field') : 'id';
$sortDirection = in_array(strtolower(request('direction')), ['asc', 'desc']) ? request('direction') : 'asc';

$company = Company::query()
    // 用where包裹orWhere,避免后续添加其他查询条件时逻辑冲突
    ->where(function ($query) {
        $search = request('search', '');
        $query->orWhere('code', 'LIKE', "%{$search}%")
              ->orWhere('description', 'LIKE', "%{$search}%")
              ->orWhere('email', 'LIKE', "%{$search}%");
    })
    ->when(request()->has(['field', 'direction']), function ($query) use ($sortField, $sortDirection) {
        $query->orderBy($sortField, $sortDirection);
    })
    ->with(['user' => fn($query) => $query->select('id', 'name', 'email')]) // PHP 7.4+ 短闭包语法
    ->paginate(5);

关键优化说明

  • 用when()替代if-else,让查询逻辑更连贯简洁
  • 验证排序字段和方向,避免SQL注入或非法参数导致的程序错误
  • 用where()包裹搜索的orWhere子句,防止后续添加其他查询条件时出现逻辑混乱
  • 给request('search')设置默认值,避免空值拼接引发的异常

内容的提问来源于stack exchange,提问作者Service Alert System

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 02:05:25