在同一表中返回父母的孩子时在嵌套循环中遇到麻烦Laravel 5.6

时间:2018-07-26 15:04:31

标签: laravel foreach eloquent relationship nested-loops

我有一张桌子@Query("_class:your package name here.AnimalEntity") public AnimalEntity findAllAnimals(); ,在这里我要把父母的孩子放在同一张桌子上。到现在为止,一切都很好,但是当我以表格形式显示这些内容时遇到了问题。我在同一张桌子上有4个或5个级别的父母子女。 我的礼物account_heads就像下面的东西

loop

我想最小化上述循环。 我想要得到的结果就像是波纹管 enter image description here

我的数据库表结构如下- enter image description here

我的帐户@foreach ($accountHeads as $accountHead) @foreach ($accountHead->children as $children) <option value="{{ $children->id }}">{{ $children->name }} @if($children->code) ({{ $children->code }})@endif</option> @foreach($children->children as $c1) <option value="{{ $c1->id }}"> -- {{ $c1->name }} @if($c1->code) ({{ $c1->code }})@endif</option> @foreach($c1->children as $c2) <option value="{{ $c2->id }}"> ---- {{ $c2->name }} @if($c2->code) ({{ $c2->code }})@endif</option> @foreach($c2->children as $c3) <option value="{{ $c3->id }}"> ------ {{ $c3->name }} @if($c3->code) ({{ $c3->code }})@endif</option> @foreach($c3->children as $c4) <option value="{{ $c4->id }}"> -------- {{ $c4->name }} @if($c4->code) ({{ $c4->code }})@endif</option> @foreach($c4->children as $c5) <option value="{{ $c5->id }}"> ---------- {{ $c5->name }} @if($c5->code) ({{ $c5->code }})@endif</option> @foreach($c5->children as $c6) <option value="{{ $c6->id }}"> ------------ {{ $c6->name }} @if($c6->code) ({{ $c6->code }})@endif</option> @endforeach @endforeach @endforeach @endforeach @endforeach @endforeach @endforeach @endforeach 的{​​{1}}方法如下-

AccountHeadsController

create模型就像是波纹管

public function create()
{

    $accountHeads = AccountHead::with('children')->where('parent_id', 0)->get();
    return view('account.account-head.create', compact('accountHeads'));
}

1 个答案:

答案 0 :(得分:1)

我自己是这样做的:

创建的帮助程序文件:App / Helpers / MyHelper.php

MyHelper.php文件:

<?php
namespace App\Helpers;

class MyHelper
{
  public static function dd($array, $step = 0)
{
    $output = '';
        foreach($array as $arr)
        {
            $output .= '<option  value="'.$arr->id.'">'.str_repeat('&nbsp;&nbsp;&nbsp;',$step). $arr->name.'</option>';
            if($arr->children)
            {
                $output .= self::dd($arr->children, $step+1);
            }
        }
    return $output;
}
}

并将其添加到别名下的/config/app.php中。

'MyHelper'  => App\Helpers\MyHelper::class,

然后在您的视图中可以使用:

<select>
 {!! MyHelper::dd($accountHeads) !!}
</select>