【发布时间】:2021-04-29 14:00:31
【问题描述】:
我有这个category 表:
| id | name | parent_id |
|---|---|---|
| 1 | Programming | 0 |
| 2 | History | 0 |
| 3 | PHP | 1 |
| 4 | Javascript | 1 |
| 6 | World history | 2 |
| 7 | jQuery | 4 |
| 8 | AJAX | 4 |
| 9 | Europe | 6 |
| 10 | American | 6 |
| 16 | ajax nested | 8 |
这是我在 controller 中获取类别的方法:
$categories = Category::where('parent_id', '=', 0)->with('childs')->get();
和型号类别:
class Category extends Model
{
use HasFactory;
protected $fillable = ['name'];
public function user()
{
return $this->belongsTo(User::class);
}
public function posts()
{
return $this->hasMany(Post::class)->orderBy('created_at', 'DESC');
}
public function childs()
{
return $this->hasMany(Category::class, 'parent_id', 'id');
}
}
我想输出类别,像这样:
<select>
<option id="1">Programming</option>
<option id="3">Programming -> PHP</option>
<option id="4">Programming -> Javascript</option>
<option id="7">Programming -> Javascript -> jQuery</option>
<option id="8">Programming -> Javascript -> AJAX</option>
<option id="16">Programming -> Javascript -> AJAX -> ajax nested</option>
<option id="2">History</option>
<option id="6">History -> World history</option>
<option id="9">History -> World history -> Europe</option>
<option id="10">History -> World history -> American</option>
</select>
看起来像: this
我正在考虑两种选择:
-
一些带有递归函数的服务和干净的php代码,它返回具有完整HTML结构的变量(选择+选项)并在模板文件中显示该变量。
-
一些 Laravel 方式,我不知道如何实现。
【问题讨论】:
-
这是我对类似问题的回答。 stackoverflow.com/a/65635958/7181149
-
虽然我只是将它们显示在列表中。
-
@AhmadKarimi 有趣的是,您可以在关卡模板上进行操作。我做了一些类似的事情来在下拉菜单中呈现它们,它工作正常 - imgur.com/a/Dt3T7zQ 我尝试做类似的事情和选择标签(模板的递归调用),但现在无法处理。
-
所以您只在将它们放入选择框时遇到问题是吗?
-
@AhmadKarimi 这就是我为菜单做的方式,类似于你的回答-pastebin.com/erDkMWZ9我不知道如何处理它们之间的箭头