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

Laravel新手求助:如何通过嵌套查询随机获取单条记录

解决方案

首先修正你的控制器代码,原代码里的first()会直接取出单个部门,后续的随机排序和数据获取逻辑完全错误,我们需要调整为随机排序部门,同时每个部门仅加载一条随机员工记录:

控制器代码修改

$alldepartments = Department::translatedIn(app()->getLocale())
    ->where('status', 1)
    ->inRandomOrder() // 随机排序所有符合条件的部门
    ->with(['employees' => function ($query) {
        // 每个部门仅关联一条随机员工
        $query->inRandomOrder()->first();
    }])
    ->get();

如果你的Laravel版本对first()在关联闭包里支持不好,可以换成limit(1):

$alldepartments = Department::translatedIn(app()->getLocale())
    ->where('status', 1)
    ->inRandomOrder()
    ->with(['employees' => function ($query) {
        $query->inRandomOrder()->limit(1);
    }])
    ->get();

Blade视图代码修改

因为现在每个部门只有一条员工记录,不需要嵌套两层循环,直接取出员工即可,同时增加判断避免无员工的部门显示空内容:

<div style="overflow-x: scroll; overflow-y: hidden; white-space: nowrap">
    <div class="d-flex flex-row flex-nowrap">
        @foreach($alldepartments as $mydepartment)
            @if($mydepartment->employees->isNotEmpty())
                @php $employee = $mydepartment->employees->first(); @endphp
                <div class="col-12 col-sm-6 col-lg-3">
                    <a href="{{ url('employee/'. $employee->id) }}">
                        <div class="single_advisor_profile wow fadeInUp" data-wow-delay="0.2s" style="visibility: visible; animation-delay: 0.2s; animation-name: fadeInUp;">
                            <div class="advisor_thumb">
                                <img src="{{ asset('uploads/employees/'.$employee->image) }}" alt="{{ $employee->name }}" />
                            </div>
                            <div class="single_advisor_details_info">
                                <h6>{{$employee->name}}</h6>
                                <p class="designation">{{$mydepartment->name}}</p>
                            </div>
                        </div>
                    </a>
                </div>
            @endif
        @endforeach
    </div>
</div>

关键说明

  • 去掉原代码中的first():它会直接获取单个部门,导致后续逻辑失效
  • 使用with()的闭包约束关联查询:确保每个部门只加载一条随机员工,同时避免N+1查询问题
  • 视图简化循环:因为每个部门只有一条员工记录,无需内层foreach

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 10:54:51