The code below works fine:
$data = Structures::select("id", "parent_id", "category", "type", "subType", "variant", "description") ->orderBy('category') ->orderBy('type') ->orderBy('subType') ->orderBy('variant') ->get() ; return $this->fillCategories($data) ;
The fillCategories()
function fills a JSON tree with parent child relationships.
However, the code below, doesn’t work.
$data = DB::table("categories AS t1") ->select("t1.id", "t1.name AS category", "t2.id as typeId", "t2.name as type", "t3.id as subTypeId", "t3.name as subType", "t4.id as variantId", "t4.name as variant") ->leftJoin("categories AS t2", "t2.parent_id", "=", "t1.id") ->leftJoin("categories AS t3", "t3.parent_id", "=", "t2.id") ->leftJoin("categories AS t4", "t4.parent_id", "=", "t3.id") ->whereNull("t1.parent_id") ->orderBy("t1.name") ->orderBy("t2.name") ->orderBy("t3.name") ->orderBy("t4.name") ->get() ; foreach ($data as $v) { Log::info("cat: " . json_encode($v)); } return $this->fillCategories($data) ;
The local log returns values, but when $data
is passed to fillCategories()
the foreach in the function ignores the $data
!
Snippet of the foreach
in fillCategories()
... $select = array() ; $child = array() ; $cat = null ; $type = null ; $sub = null ; $first = true ; $clear = true ; $label = null ; $value = null ; $prev = null ; Log::info("fillCat: data = " . json_encode($data)) ; foreach ($data as $v): Log::info("fillCat forloop: v($v->cat, $v->type, $v->subType, $v->variant)") ; $parent = null ; $isKid = false ; $isGrandKid = false ; ...
I’m assuming for now that passing $data
to the function from DB::table
rather than FacadesAppModelStructures::get()
somehow gets lost in translation.
Advertisement
Answer
Thanks Faiz, apparently orderBy
was the issue! (!) If I take it out, fillCategories()
the foreach
processes the data.
$data = DB::table("categories AS t1") ->select("t1.id", ...) ->leftJoin("categories AS t2", "t2.parent_id", "=", "t1.id") ->leftJoin("categories AS t3", "t3.parent_id", "=", "t2.id") ->leftJoin("categories AS t4", "t4.parent_id", "=", "t3.id") ->whereNull("t1.parent_id") ->orderBy("t1.name") ->orderBy("t2.name") ->orderBy("t3.name") ->get() ;
This works. Maybe Taylor Otwell can tell me why!