私は、次のワークフローを達成するために、多くの関係に多くを使用しようとしている:Laravel入れ子になったのForEach以上雄弁コレクション
多くのセクションと、多くのユーザーがあります。各ユーザーには、ロックを解除したセクションがあります。たとえば、2つのセクション(セクションIとセクションII)がある場合、最初のユーザーJim(
id = 1
)はセクションXのロックを解除し、2番目のユーザーDebbie(id = 2
)はセクションIとIIをロック解除しました。これを達成するために、私は3つの次に、データベース、標準Laravel
users
、セクションデータを格納sections
(セクションI、セクションIIのid = 2
ためid = 1
)、次いでIが正常に関節として使用した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();
}
ユーザーデビーのための私の播種はここにある:
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つだけがロックされています。周りを壊す。
ありがとうございます、正しい方向に大きなステップ! –