2017-03-29 7 views
0

私は、次のワークフローを達成するために、多くの関係に多くを使用しようとしている:Laravel入れ子になったのForEach以上雄弁コレクション

  1. 多くのセクションと、多くのユーザーがあります。各ユーザーには、ロックを解除したセクションがあります。たとえば、2つのセクション(セクションIとセクションII)がある場合、最初のユーザーJim(id = 1)はセクションXのロックを解除し、2番目のユーザーDebbie(id = 2)はセクションIとIIをロック解除しました。これを達成するために

  2. 、私は3つの次に、データベース、標準Laravel users、セクションデータを格納sections(セクションI、セクションIIのid = 2ためid = 1)、次いでIが正常に関節として使用したuser_sectionを有しますテーブル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は両方のセクションを結合テーブルに持っていますが、そのうちの1つだけがロックされています。周りを壊す。

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

ありがとうございます、正しい方向に大きなステップ! –