【问题标题】:Laravel Nested ForEach Over Eloquent CollectionLaravel 在 Eloquent 集合上嵌套 ForEach
【发布时间】:2017-03-29 09:50:40
【问题描述】:

我正在尝试使用多对多关系来完成以下工作流程:

  1. 有很多部分和很多用户。每个用户都有他们已解锁的部分。例如,如果有两个部分(部分 I 和部分 II),第一个用户 Jim (id = 1) 已解锁部分 X,第二个用户 Debbie (id = 2) 已解锁部分 I 和 II。

  2. 1234563 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();
    }

我为用户 Debbie 播种在这里:

        DB::table('user_section')->insert([
            'user_id' => 2,
            'section_id'=>1
        ]);
        DB::table('user_section')->insert([
            'user_id' => 2,
            'section_id'=>2
        ]);

但我以 Debbie 身份登录时得到以下结果:

因此,即使 Debbie 在连接表中同时拥有这两个部分,但她只解锁了其中一个部分,如果我删除或移动休息区,情况也会再次发生变化。

【问题讨论】:

    标签: php arrays laravel-5


    【解决方案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();
    

    这将为您提供所有部分,并急切加载用户关系,即当前用户。因此,如果用户关系为空,则当前用户尚未解锁该部分。

    【讨论】:

      猜你喜欢
      • 2021-08-11
      • 2018-05-13
      • 2019-07-25
      • 2021-08-23
      • 1970-01-01
      • 2018-05-27
      • 2015-06-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多