Laravel Jetstream比对两表数据实现表格单元格背景变色问题
问题根因
你在<td>的style属性内嵌套了@foreach循环遍历关联用户ID数组,每次比对都会重新赋值background属性,前面的匹配结果会被后续循环的判断结果覆盖,最终只有数组最后一个元素的比对结果会生效,因此只有和数组最后一个user_id匹配的单元格才能正确显示蓝色背景。
修复步骤
1. 修改Blade模板中对应单元格的样式逻辑
直接用集合的contains()方法判断当前用户ID是否存在于关联用户ID集合中,无需嵌套循环:
<td class="px-6 py-4 text-sm whitespace-no-wrap" style="background: {{ $isUsersHaveAffliatedOrganization->contains($item->id) ? 'blue' : 'red' }}"> <x-jet-button wire:click="addShowOrganizationModel({{ $item->id }})"> {{__('Add Organization')}} </x-jet-button> </td>
如果你后续把关联ID集合转为纯数组,也可以用PHP原生的in_array方法判断:
style="background: {{ in_array($item->id, $isUsersHaveAffliatedOrganization) ? 'blue' : 'red' }}"
2. 可选优化:简化控制器查询逻辑
你查询关联用户ID的方法里不需要先get()再pluck(),也不需要排序(只判断存在性的话排序无意义),可以直接简化:
public function isUserHaveOganization(){ $this->isUserOrgAuthId = DB::table('organization_user')->pluck('user_id'); return $this->isUserOrgAuthId; }
内容的提问来源于stack exchange,提问作者Jonathan Cruz
相关产品推荐
相关产品推荐

