나는 다음과 같은 워크 플로우를 달성하기 위해 많은 관계로 많은 사용하려고 해요 :Laravel 중첩 된 foreach는 이상 설득력 컬렉션
많은 섹션과 많은 사용자가 있습니다. 각 사용자에게는 잠금 해제 된 섹션이 있습니다. 예를 들어 첫 번째 사용자 인 Jim (
id = 1
)이 두 번째 섹션 (X 섹션 잠금 해제)을 가지고 있고 두 번째 사용자 인 Debbie (id = 2
) 섹션 I과 II의 잠금이 해제되어 있습니다.- 난 세 개의 데이터베이스가,이를 달성하기 위해, 표준 Laravel
users
은 다음 섹션 데이터를 저장하는sections
(섹션id = 1
는 I 및 제 II 용id = 2
) 다음user_section
는 I 성공적으로 관절로 사용했는지 표는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();
}
사용자 데비에 대한 나의 파종은 여기에 있습니다 :
DB::table('user_section')->insert([
'user_id' => 2,
'section_id'=>1
]);
DB::table('user_section')->insert([
'user_id' => 2,
'section_id'=>2
]);
,
Debbie로 로그인하면 다음과 같은 결과가 나타납니다.
그래서 Debbie는 두 섹션을 모두 조인 테이블에 넣었지만 그 중 하나만 잠금 해제되며 다시 제거하거나 이동하면 변경됩니다 돌아 다니다.
감사합니다, 올바른 방향으로 큰 걸음 걸이! –