如何使用mysql在laravel中编写嵌套的while循环

时间:2018-02-22 20:07:20

标签: php sql laravel laravel-5

谁能告诉我如何在laravel中转换这个伪代码?像内部循环sql表条件取决于来自父循环的值。

while($row1 = mysqli_fetch_array($result)
{ 
      $query = select * from table where id=$row['id];
       $result2 = mysqli_query($query,$conn);

        while($row2 = mysqli_fetch_array($result2)
         {
             echo $row2['id'];
         }

}

任何想法?

1 个答案:

答案 0 :(得分:0)

最好的方法是使用Eloquent relationships,如下所示:

在您的控制器中:

$companies = Company::with('projects.tasks')->get();
return view('yourview', compact('companies'));

在你看来

@foreach($companies as $company)
    @foreach($company->tasks as $task)
        <p>{{$company->name}} {{$task->name}} </p>
    @endforeach
@endforeach