[英]Comparing two models in Laravel/Eloquent
I have the table item_list
and the table users
我有表
item_list
和表users
I have the pivot table allowed_items
that contains item_id
from the item_list and user_id
from the user table. 我有透视表
allowed_items
包含item_id
从item_list和user_id
从用户表。
I have some checkbox list that should be checked when the item and the user are in the pivot table, and be left unchecked if it does not. 我有一些复选框列表,当项目和用户位于数据透视表中时应选中该复选框,如果没有,则保持选中状态。
I am currently doing this: 我目前正在这样做:
$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;
}
Then I return the view and check if the item exists like this: 然后,我返回视图并检查项目是否存在,如下所示:
@foreach($items as $item)
<input type="checkbox" value="{{$item->id}}
{{array_key_exists($item->id,$allow_array") ? "checked":" "}}>
@endforeach
This works, but it feels unprofessional. 这可行,但是感觉很不专业。 Any way to do this in the controller?
有什么办法在控制器中做到这一点?
If you want a cleaner code you can make into the Item controller a new method call eg isAllowed which will return a boolean function. 如果您想要更简洁的代码,则可以在Item控制器中添加一个新的方法调用,例如isAllowed,它将返回一个布尔函数。
Item controller 项目控制器
public function isAllowed(){
// check if exists and return yes/no
}
Template 模板
@foreach($items as $item)
<input type="checkbox" value="{{$item->id}}
{{$item->isAllowed() ? "checked":" "}}>
@endforeach
If you can give us more details I'll edit my answer to properly answer your question. 如果您可以提供更多详细信息,我将编辑我的答案以正确回答您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.