创建子母公司Laravel的无限嵌套层次结构数组

时间:2019-01-14 07:30:24

标签: php laravel sorting parent-child

我有一个表company_basics,其中有parent_id,这种子对父母的关系可以不受限制。

当前,我的代码是

$company = \App\CompanyBasic::whereRaw('user_id = ' . Auth::user()->id . " AND parent_id = 0")->get();


//                echo "<pre>";
//                print_r($company);
//                echo "</pre>";

$companies = array();
$count = 0;
foreach($company as $single_company) {
    $companies[$count]['id'] = $single_company->id;
    $companies[$count]['comp_name'] = $single_company->comp_name;

    $child_company = \App\CompanyBasic::whereRaw('user_id = ' . Auth::user()->id . " AND parent_id = '" . $single_company->id . "'")->get();

    $child_count = 0;
    foreach($child_company as $single_child_company) {
        $companies[$count]['child'][$child_count]['id'] = $single_child_company->id;
        $companies[$count]['child'][$child_count]['comp_name'] = $single_child_company->comp_name;
        $child_count++;
    }

    echo "company id: " . $single_company->id . "<br>";
    $count++;
}

我只能让父母陪伴,并通过他们寻找孩子,但这是一个级别的下调,但我想无限地向下移动。

现在返回的代码是

Array
(
    [0] => Array
        (
            [id] => 2
            [comp_name] => Habib company
            [child] => Array
                (
                    [0] => Array
                        (
                            [id] => 16
                            [comp_name] => Child Company
                        )

                    [1] => Array
                        (
                            [id] => 18
                            [comp_name] => Child Company
                        )

                )

        )

    [1] => Array
        (
            [id] => 15
            [comp_name] => Adjacent Company
        )

    [2] => Array
        (
            [id] => 17
            [comp_name] => MSB34
        )

)

1 个答案:

答案 0 :(得分:2)

按照@rypskar的建议,您应该使用递归。

我建议您使用anonymous function并将其内部使用(称为closure),并执行以下操作:

 $userId = Auth::user()->id;

 $getChildOf = function ($parent) use ($userId, &$getChildOf) {

        $company   = \App\CompanyBasic::whereRaw('user_id = ' . $userId . " AND parent_id = " . $parent)->get();
        $companies = false;

        if ($company->isNotEmpty()) {
            $companies = array();

            foreach ($company as $single_company) {
                $companies[] = array(
                    'id'        => $single_company->id,
                    'comp_name' => $single_company->comp_name,
                    'child'     => $getChildOf($single_company->id),
                );
                echo "company id: " . $single_company->id . "<br>";
            }
        }

        return $companies;
  };

 $companies = $getChildOf(0);

这里,匿名函数传递给变量$getChildOf,该变量用于自身。

我已删除您的$count变量以简化代码。

顺便说一句,您应该了解该代码将在每次迭代时执行数据库查询,因此将大大增加服务器负载

此外,通过串联向SQL查询中注入变量是不安全的,并且被认为是不好的做法。您应该考虑使用prepared statements