【问题标题】:Foreach inside Foreach based on column value基于列值的 Foreach 内部的 Foreach
【发布时间】:2021-06-24 01:46:12
【问题描述】:

我有一个这样的 sql 表知识库

id、categoryid、标题

id categoryid title
1 1 apple
2 1 fb
3 2 google
4 2 DB
5 3 Reebok

在我的 laravel 刀片中,我正在尝试创建一个如下所示的树视图

-1
--apple
--FB
-2
--google
--DB
-3
--Reebok

我的控制器执行基本查询并将整个表返回给视图。到目前为止,我是 laravel 的新手,我可以得到一个基本的表来工作

@foreach($knowledgebase as $key => $value)
<tr>
    <td>{!! $knowledgebase ->id !!}</td>
    <td>{!! $knowledgebase ->title!!}</td>
    <td>{!! $knowledgebase ->categoryid !!}</td>
</tr>
@endforeach

我将如何迭代 categroyid 列,显示第一个类别和所有子标题,然后转到下一个 categoryid。

更新

public function show($id) {

    //get article
    $knowledgebase = \App\Models\Knowledgebase::Where('knowledgebase_slug', request('knowledgebase_slug'))->first();

return view('knowledgebase', compact('knowledgebase'));

}

【问题讨论】:

  • 你也可以展示你的控制器吗?
  • 请你的模型和迁移,也许你必须自己加入模型/表

标签: laravel foreach eloquent model


【解决方案1】:
You will need to retrieve in controller the categories before ($categories)
@foreach($categories as $category)
   <tr>
      <td>{{ $category->id }}</td>
      <td>{{ $category->title}}</td>
      <td>{{ $category->categoryid }}</td>
   </tr>
@endforeach

【讨论】:

  • 同一张桌子。当所有类别都在同一个表中时,我不确定如何单独检索类别。
【解决方案2】:

无论如何,我设法通过在我的模型中添加函数 children 来解决这个问题。所以在我的模型中添加了

public function children(){
return $this->hasMany('App\Models\Knowledgebase', 'categoryid');
}

在此之后,我只是在我的 foreach 中将其称为 foreach

@foreach($categories as $category)
<li><a href="#">{{ $category->title}}</a></li>
@if($category->children)
@foreach($category->children as $child)
<ul>
<li class="pl-3"><a href="#"> {{ $child->title}} </a></li>
</ul>
@endforeach
@endif
@endforeach

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-14
    • 1970-01-01
    相关资源
    最近更新 更多