我怎么能一次删除一个函数/方法,却使用这个多查询Laravel



这是我的users

1.id
2.name
3......

我的branches

1.id
2.branch_name
3....

members

1.id
2.branch_id
3.user_id
4.member_name
5......

一个数据透视表名称branch-users

1.id
2.user_id
3.branch_id

branch_user数据透视表中用户存储的允许分支id,当该用户输入任何成员时,他只能在<select></select>字段中看到他的分配分支列表,或者如果想查看成员列表。他只能看到他的分配分支成员列表。我已经在Laravel控制器中实现了这样的查询

我的索引方法部分

public function index(){
$my = Auth::user()->branches;// branches is a many to many relation method in user model
foreach($my as $my){
$myBranch[] = $my->id;
}
$member = Member::whereIn('branch_id',$myBranch)->get();
return view('member.create',compact('member'))
}

我的创建方法部分

public function create(){
// i have to check every where this section...from....... 
$my = Auth::user()->branches;
foreach($my as $my){
$myBranch[] = $my->id;
}
//.......to here
$branch = Branch::whereIn('id',$myBranch)->get();
return view('member.create',compact('branch'))
}

我的问题是,我想使用这个::whereIn('branch_id',$myBranch)->....where条件来显示分支列表和分支成员列表,无论在哪里我都必须声明和检查Laravel框架中不好的用户分配分支列表,我知道有机会我可以一次声明任何函数,并且可以多次使用该函数/方法/变量。我想检查一下,一次身份验证的用户分配分支id,并在需要的地方使用多次。但不幸的是,我不明白我该怎么做。如果有人理解我想说的话,请帮帮我。

您可能想为自己编写一个本地范围查询。您将部分查询逻辑放在模型上,然后可以在任何试图查询该模型的地方调用它。

https://laravel.com/docs/5.7/eloquent#local-示波器

最新更新