[英]Laravel Nested ForEach Over Eloquent Collection
我正在尝试使用多对多关系来完成以下工作流程:
有很多部分和许多用户。 每个用户都有解锁的部分。 因此,例如,如果有两个部分(第一部分和第二部分),则第一个用户Jim( id = 1
)已解锁第X部分,第二个用户Debbie( id = 2
)已解锁了第一部分和第二部分。
为了实现这一点,我有三个数据库,一个标准Laravel users
,则一个sections
,其存储部的数据( id = 1
为第I和id = 2
为II段),然后user_section
,我已成功地用作关节表在User
模型和Section
模型之间。 该联接表是用户和节混合的地方,如果该节中有给定user_id
的条目,则相应的section_id
被解锁。
我具有以下功能:1.获取视图的所有部分,以及2.让用户知道其中哪些部分已解锁。
问题是我出现了重复的节,所以它会说节I已解锁,然后节I都被锁定在同一视图中,这一定是我遍历和比较数组的方式。 通过对代码进行调整(我可以在其中放置一个break
,可以消除重复项,但是错误的部分将被锁定。
我的逻辑在这里:
public function getSections(){
$arrayofuserSections = array();
$tempArray = array();
$user = User::where("id",Auth::user()->id)->first();
foreach ($user->section as $section) {
$tempArray['Name'] = $section["name"];
$tempArray['Goals'] = $section["goals"];
array_push($arrayofuserSections,$tempArray);
}
$finarray = array();
$sections=Section::orderBy('order')->get();
foreach ($sections as $section) {
foreach($arrayofuserSections as $arraysection){
if($section->name == $arraysection["Name"])
{
$arraysection["Unlocked"] = 1;
array_push($finarray,$arraysection);
}
else{
$arraysection["Unlocked"] = 0;
$arraysection["Name"] = $section->name;
$arraysection["Goals"] = "";
array_push($finarray,$arraysection);
}
break;
}
}
return $finarray;
}
$user->section
源自User
模型上的方法,此处:
public function section()
{
return $this->belongsToMany('App\Models\Section','user_section')->withTimestamps();
}
我为用户Debbie播下的种子在这里:
DB::table('user_section')->insert([
'user_id' => 2,
'section_id'=>1
]);
DB::table('user_section')->insert([
'user_id' => 2,
'section_id'=>2
]);
但是,以Debbie登录时,我得到以下结果:
因此,即使黛比在联接表中同时拥有了这两个部分,但她却只有其中一个被解锁,如果我删除或移动中断,这种情况也会再次改变。
我认为您是从错误的方向来的。
如果您正确设置了关系,则应该能够访问用户的部分以及部分的用户。
// Find user with sections they have unlocked
$user = User::with('sections')->findOrFail(1);
// Find sections with users who have unlocked them
$section = Section::with('users')->findOrFail(1);
如果从各节的方向解决此问题,则可以执行以下操作:
// Find current user id
$userId = Auth::id();
// Find all sections with users who have unlocked them, limited to only the current user
$sections = Section::with([
'users' => function ($query) use ($userId) {
return $query->where('id', $userId);
}
])->get();
这将为您提供所有部分,并渴望加载用户关系,即当前用户。 因此,如果用户关系为空,则当前用户尚未解锁该部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.