2017-03-29 2 views
0

나는 다음과 같은 워크 플로우를 달성하기 위해 많은 관계로 많은 사용하려고 해요 :Laravel 중첩 된 foreach는 이상 설득력 컬렉션

  1. 많은 섹션과 많은 사용자가 있습니다. 각 사용자에게는 잠금 해제 된 섹션이 있습니다. 예를 들어 첫 번째 사용자 인 Jim (id = 1)이 두 번째 섹션 (X 섹션 잠금 해제)을 가지고 있고 두 번째 사용자 인 Debbie (id = 2) 섹션 I과 II의 잠금이 해제되어 있습니다.

  2. 난 세 개의 데이터베이스가,이를 달성하기 위해, 표준 Laravel users은 다음 섹션 데이터를 저장하는 sections (섹션 id = 1는 I 및 제 II 용 id = 2) 다음 user_section는 I 성공적으로 관절로 사용했는지 표는 UserSection 모델 사이에 있습니다. 이 조인 테이블은 사용자와 섹션이 서로 섞여있는 곳이며 해당 섹션에 주어진 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는 두 섹션을 모두 조인 테이블에 넣었지만 그 중 하나만 잠금 해제되며 다시 제거하거나 이동하면 변경됩니다 돌아 다니다.

Console Log

답변

1

난 당신이 잘못된 방향에서이오고 있다는 것을 생각합니다.

관계를 올바르게 설정했다면 사용자의 섹션과 섹션의 사용자에게 액세스 할 수 있어야합니다.

// 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(); 

등을 열망 부하 즉 현재는 사용자의 관계, 사용자. 따라서 사용자 관계가 비어 있으면 현재 사용자가 해당 섹션의 잠금을 해제하지 않은 것입니다.

+0

감사합니다, 올바른 방향으로 큰 걸음 걸이! –