【发布时间】:2021-01-19 05:19:46
【问题描述】:
下面的代码可以正常工作:
$data = Structures::select("id", "parent_id", "category", "type", "subType", "variant", "description")
->orderBy('category')
->orderBy('type')
->orderBy('subType')
->orderBy('variant')
->get() ;
return $this->fillCategories($data) ;
fillCategories() 函数使用父子关系填充 JSON 树。
但是,下面的代码不起作用。
$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) ;
本地日志返回值,但是当$data传递给fillCategories()时,函数中的foreach忽略了$data!
fillCategories() 中 foreach 的片段
...
$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 ;
...
我现在假设将 $data 从 DB::table 而不是 Facades\App\Model\Structures::get() 传递给函数会在翻译中丢失。
【问题讨论】:
-
它们是不同的查询,可能一个没有返回任何结果
-
感谢您的评论。这是我最初的想法。他们都返回结果。我查过了。
-
那么这里还不够......你将一个集合传递给这个方法,如果它不为空,那么
foreach将运行(迭代它),所以根据你的正在显示集合必须为空才能到达该日志语句 -
[2020-10-04 08:13:42] local.INFO: fillCat: data = [{"id":11,"parent_id":null,"category":"Structure", "type":"Lampole","subType":null,"variant":null,"description":"Lampole"},{"id":13,"parent_id":11,"category":"Structure", "type":"Lampole","subType":"QB","variant"[2020-10-04 08:13:42] local.INFO: fillCat: data = [{"id":297,"category" :"建筑物","typeId":297,"type":"Cabin","subTypeId":null,"subType":null,"variantId":null,"variant":null},{"id":311 ,"category":"建筑物","typeId":311,"type":"守卫
-
好的,它正在达到它......那么问题是什么?
标签: php laravel eloquent php-7 laravel-7