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

Laravel9中如何查询指定客户名称的列?代码返回空数组求助

问题分析与解决

你的代码当前是查询client_name等于空字符串的记录,这和你要找包含指定客户名称的需求完全不符,所以返回空数组是正常的。

要实现包含指定客户名称的查询,需要用模糊匹配,Laravel提供了两种常用实现方式:

方式一:使用like运算符

如果需要从请求中获取要查询的客户名称(比如通过GET/POST参数传递),可以这样写:

public function clientname()
{
    // 从请求中获取目标客户名称,例如通过http://your-domain.com/clientname?name=张三传递参数
    $targetName = request()->input('name');
    
    // 用%通配符实现模糊匹配,匹配包含目标名称的所有记录
    $clients = Commande::where('client_name', 'like', "%{$targetName}%")->get();
    
    return response()->json($clients);
}

方式二:使用Laravel 9+的whereLike方法(更简洁)

Laravel 9及以上版本支持whereLike语法,写法更直观:

public function clientname()
{
    $targetName = request()->input('name');
    
    $clients = Commande::whereLike('client_name', $targetName)->get();
    
    return response()->json($clients);
}

额外说明

  • 如果你的目标客户名称是固定值,直接把$targetName换成固定字符串即可,比如"%张三%"
  • 确认数据库的client_name字段中确实存在包含目标名称的记录,否则依然会返回空数组

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 19:24:26