Laravel:将结果组合在嵌套的foreach中

时间:2017-12-13 18:09:16

标签: jquery laravel join foreach nested

我试图根据甘特图(http://thegrubbsian.github.io/jquery.ganttView/example/index.html)创建一个任务查看器

所以我有我的Works表和任务表(带有work_id)

我需要将数据传递给Gant Jquery:

var ganttData = [
{
    id: 1, name: "Feature 1", series: [
        { name: "Planned", start: new Date(2010,00,01), end: new Date(2010,00,03) },
        { name: "Actual", start: new Date(2010,00,02), end: new Date(2010,00,05), color: "#f0f0f0" }
    ]
},
{
    id: 2, name: "Feature 2", series: [
        { name: "Planned", start: new Date(2010,00,05), end: new Date(2010,00,20) },
        { name: "Actual", start: new Date(2010,00,06), end: new Date(2010,00,17), color: "#f0f0f0" },
        { name: "Projected", start: new Date(2010,00,06), end: new Date(2010,00,17), color: "#e0e0e0" }
    ]
}

在我的任务控制器中,我有这个:

$data['works'] = DB::table('works')
                 ->where('country', 'France')
                 ->get();

在我看来,我有这个:

$data = [];
foreach ($works as $work)
{
$data[] = [
    'id' => $work->id,
    'name' => $work->name,
    'series' => [
      HELP!!!
      'description' => ....,
      'startdate' => ....,
      'enddate' => ....,
    ]
];
};
?>
<script type="text/javascript">

var data = <?php echo json_encode($data); ?>;

我的问题是在SERIES添加sub foreach。在这里,我需要添加所有任务WHERE(&#39; work_id&#39;,$ work-&gt; id)

我怎样才能做到这一点?

非常感谢!

1 个答案:

答案 0 :(得分:0)

好的,我想出了一对多的关系。

我的问题是我正在使用CRUDBOOSTER并且我的控制器中的返回视图是错误的...

型号:

public function tasks(){
 return $this->hasMany('App\Task');
}

控制器:

$works = Work::all();
return view('tasks.index')->with('works', $works);

在View中我可以使用:

@foreach($works as $work)
 {{$work->id}}
 @foreach($work->tasks as $task)
  {{$task->id}}
 @endforeach
@endforeach

但是我不能在另一个foreach中使用1个foreach来制作我的数组:

<?php
$data = [];
foreach ($works as $work)
{
$data[] = [
    'id' => $work->id,
    'name' => $work->name,
    'series' => [
      foreach ($work->task as $task) {
          'name' => $task->description
        }
    ]
];
};

我得到了

  

解析错误:语法错误,意外的'foreach'(T_FOREACH),期待']'