Php 在Laravel/Elount中比较两种模型

Php 在Laravel/Elount中比较两种模型,php,laravel,Php,Laravel,我有表项目列表和表用户 我有透视表允许的\u项,其中包含来自项目列表的项目id,以及来自用户表的用户id 我有一些复选框列表,当项目和用户在透视表中时应该选中,如果不在透视表中,则不选中 我目前正在这样做: $items = item_list::all(); $allowed_items = allowed_items->where("user_id",$user_id")->get(); foreach ($allowed_item as $allow) { $allow_arr

我有表
项目列表
和表
用户

我有透视表
允许的\u项
,其中包含来自项目列表的
项目id
,以及来自用户表的
用户id

我有一些复选框列表,当项目和用户在透视表中时应该选中,如果不在透视表中,则不选中

我目前正在这样做:

$items = item_list::all();
$allowed_items = allowed_items->where("user_id",$user_id")->get();
foreach ($allowed_item as $allow)
{
$allow_array[$allow->item_id] = true;
}
然后返回视图并检查项目是否存在,如下所示:

@foreach($items as $item)
<input type="checkbox" value="{{$item->id}} 
{{array_key_exists($item->id,$allow_array") ? "checked":" "}}>
@endforeach
@foreach($items作为$item)
@endforeach

这是可行的,但感觉不专业。有没有办法在控制器中执行此操作?

如果您想要更干净的代码,您可以在项目控制器中创建一个新的方法调用,例如isAllowed,它将返回一个布尔函数

项目控制器

public function isAllowed(){
// check if exists and return yes/no
}
模板

@foreach($items as $item)
   <input type="checkbox" value="{{$item->id}} 
   {{$item->isAllowed() ? "checked":" "}}>
@endforeach
@foreach($items作为$item)

仅供参考,在控制器中执行此操作也是不专业的。我建议使用返回的集合来过滤或映射结果。它不是返回集合,而是检查数据透视表中是否存在条目,并将返回布尔值