Laravel 控制器中的 foreach

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30011700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:29:10  来源:igfitidea点击:

foreach in laravel controller

phplaravellaravel-4laravel-5

提问by Just User

I try to loop over foreach in my Registration Controller as the following

我尝试在我的注册控制器中循环 foreach,如下所示

      $subjectStartID  = Input::get('substID');

      $subjectStart = SubjectStart::find($subjectStartID);

    //To get division_ids by the relationships using SubjectStartID
       $divisionIDs =$subjectStart->teachersubject->subject->divisions ;

    // loop over $divisionIDs to get div_ids 
    foreach ($divisionID as $div) 
        {
          $div->id ;  
        }

       return var_dump($div->id);

OR

或者

      return var_dump([$div->id]);

The isuue that the result of the loop get the last id only ,
for example if the div_ids (1,2) the result is (2)

循环的结果只得到最后一个id的问题,
例如如果div_ids(1,2)结果是(2)

i need foreach to get the div_ids to use it in the following joinQuery

我需要 foreach 来获取 div_ids 以在以下 joinQuery 中使用它

 $check = Registration::join('student', 'student.id' ,'=' , 'registration.student_id')
                      ->join('division', 'division.id' ,'=' , 'student.division_id')
                      ->where('student.id' , $registerID->student_id)
                      ->whereIn('student.division_id',[$div->id])->get();

Any Suggestions ?

有什么建议 ?

回答by Mohd Abdul Mujib

I can't say about laravel, but from a phpstandpoint, you should use a container array to store all the ids returned in the foreach loop.

我不能说 laravel,但从一个php角度来看,您应该使用容器数组来存储在 foreach 循环中返回的所有 id。

imho, so your code should look like the following...

恕我直言,所以你的代码应该如下所示......

 $subjectStartID  = Input::get('substID');

  $subjectStart = SubjectStart::find($subjectStartID);

//To get division_ids by the relationships using SubjectStartID
   $divisionIDs =$subjectStart->teachersubject->subject->divisions ;



$studivs = array();
// loop over $divisionIDs to get div_ids 
foreach ($divisionID as $div) 
    {
     $studivs[] = $div->id ;  
    }

So now the variable $studivshas all the ids that you need.

所以现在该变量$studivs具有您需要的所有 ID。