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

Laravel带条件Join查询返回空数组的问题求助

问题解决:查询有订单的客户数据

你的代码返回空数组的核心问题是加了错误的筛选条件:

  • 你写的->where('commande.id_cli', '')是在找订单表中id_cli为空字符串的记录,这和你要获取“有订单的客户”的需求完全相反。
  • 另外join('clients', 'commande.id_cli', '=', 'clients.id')已经通过关联条件筛选出了有对应订单的客户,不需要额外加这个错误的where条件。

下面是两种修正方案:

方案1:基础关联查询(去重客户)

如果你只需要有订单的客户数据,且避免同一个客户因多个订单重复返回,用这个写法:

public function clientcmd()
{
    $client = Commande::join('clients', 'commande.id_cli', '=', 'clients.id')
        ->select('clients.*')
        ->distinct() // 确保每个客户只返回一次
        ->get();
    return response()->json($client);
}

方案2:Eloquent关联写法(更简洁推荐)

如果你的模型已经定义了关联关系,代码会更清晰:
先在Commande模型里定义关联:

public function client()
{
    return $this->belongsTo(Client::class, 'id_cli');
}

再在Client模型里定义反向关联:

public function commandes()
{
    return $this->hasMany(Commande::class, 'id_cli');
}

然后查询代码可以改成:

public function clientcmd()
{
    // 直接获取所有有订单的客户,自动去重
    $clients = Client::whereHas('commandes')->get();
    return response()->json($clients);
}

内容的提问来源于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.20 22:18:27