Laravel使用distinct()查询时如何在不同program_id条件下获取branch_id值
问题原因
你当前的查询仅通过select('program_id')指定返回program_id字段,得到的Peserta模型实例不包含branch_id的值,即便写了with('branch')也无法正常加载branch关联,因为关联依赖的外键branch_id没有被查询出来。
解决方法
1. 调整查询语句
把branch_id加入select查询字段,distinct会自动对program_id + branch_id的组合值去重,刚好满足你获取不同program_id对应branch_id的需求:
$data = Peserta::where('branch_id', $branch_id) ->select('program_id', 'branch_id')->distinct() ->with('program', 'branch');
2. 修复闭包变量引入问题
你当前代码中action列的闭包直接使用了外部变量$branch_id,需要用use引入才能正常调用,否则会抛出变量未定义的错误:
->addColumn('action', function ($data) use ($branch_id) { $btn = '<a href="/halaman-data-peserta-berdasarkan-cabang-dan-program/'.$branch_id.'/'.$data->program->id.'" class="btn btn-sm btn-info"> check </a>'; return $btn; })
拓展场景
如果你不需要限制固定的branch_id查询,直接删除where('branch_id', $branch_id)条件即可,查询结果会返回所有program_id和对应关联的branch_id的去重记录。
如果你只需要拿到program_id和branch_id的映射数组,可以直接用pluck方法:
$programBranchMap = Peserta::select('program_id', 'branch_id') ->distinct() ->pluck('branch_id', 'program_id');
内容的提问来源于stack exchange,提问作者Febri Tahta
相关产品推荐
相关产品推荐

