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

Laravel中whereIn筛选关联客户列表失败问题求助

问题:Laravel中通过whereIn关联同公司客户列表失败

我需要获取当前登录用户所属公司的客户列表,已经拿到了登录用户的公司信息并筛选出了同公司的用户,但用foreach结合whereIn关联客户时一直失败。我怀疑是语法问题,因为得到的是对象而非数组,所有变量都已经正确取值,作为Laravel新手希望得到帮助。

尝试的代码片段

初始化变量

@php
$stage = 1;
$company_user= Auth::user()->company;;
$related_users= $users->where('company', $company_user);
@endphp

三种错误的foreach写法

@foreach ($customers->where('stage', $stage)->whereIn('user_registered', $related_users) as $customer)
@endforeach
@foreach 
($customers->where('stage', $stage)->whereIn('user_registered', $related_users()->id) as $customer)
@endforeach
@foreach 
($customers->where('stage', $stage)->whereIn('user_registered', array($related_users)) as $customer)
@endforeach

解决方案

问题核心是$related_users是集合对象,而whereIn方法需要接收一个纯ID数组,不是集合或对象。

视图内修正写法

先把同公司用户的ID提取成数组:

@php
$stage = 1;
$company = Auth::user()->company;
// 提取同公司用户的ID数组
$related_user_ids = $users->where('company', $company)->pluck('id')->toArray();
@endphp
  • pluck('id')从集合中取出所有用户的ID,返回一个集合;
  • toArray()将集合转换为纯PHP数组,满足whereIn的参数要求。

之后在foreach中使用这个数组:

@foreach ($customers->where('stage', $stage)->whereIn('user_registered', $related_user_ids) as $customer)
    {{-- 这里编写客户信息展示代码 --}}
@endforeach

推荐优化:控制器处理逻辑

Laravel最佳实践是尽量减少视图中的业务逻辑,建议把查询逻辑移到控制器:

// 对应控制器方法
public function index()
{
    $stage = 1;
    $company = auth()->user()->company;
    // 直接查询同公司用户的ID数组
    $related_user_ids = \App\Models\User::where('company', $company)->pluck('id')->toArray();
    // 提前筛选符合条件的客户
    $customers = \App\Models\Customer::where('stage', $stage)->whereIn('user_registered', $related_user_ids)->get();
    
    return view('你的视图名称', compact('customers'));
}

视图中直接循环处理好的客户集合:

@foreach ($customers as $customer)
    {{-- 展示客户内容 --}}
@endforeach

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 11:10:40