【问题标题】:Can Anyone help me to bring a tree structure in laravel like this任何人都可以帮我在laravel中带来这样的树结构吗
【发布时间】:2019-11-25 21:32:10
【问题描述】:

期望的输出是这样的:

Parent Cat 1
Parent Cat 2
    Child Cat 1
    Child Cat 2
Parent Cat 3
    Child Cat 3

但我需要这样做,而表结构如下所示

   id  | cat_name      | cat_parent_id
   --- | --------------| ------------- 
   1   | Parent Cat 1  | NULL 
   2   | Parent Cat 2  | NULL 
   3   | Child Cat 1   | 2 
   4   | Child Cat 2   | 2 
   5   | Parent Cat 3  | NULL 
   6   | Child Cat 3   | 5

表结构是这样的

我想在刀片视图中获得如下输出:

所有父母在表格中的 Laravel 视图:

Parent Cat 1
Parent Cat 2
Parent Cat 3

所有孩子的 Laravel 表格视图:

Child Cat 1
Child Cat 2
Child Cat 3

如何在基于所有父母的上述结构上得到这样的

【问题讨论】:

  • 你可以在你的表上做一个内连接来获取需要的数据来开始
  • 父母和孩子都在一个表中,我在laravel中使用雄辩的orm来获取laravel树
  • 您想单独获取它们还是在一个雄辩的查询中获取它们?原因是结构和示例描述性不够。
  • 我使用下面的代码作为 orm public function childs() { return $this->hasMany('App\Model\clients','under_reference','reference_id','id')- >leftjoin('clients_payment_type', function($join) { $join->on('clients_payment_type.user_id', '=', 'clients.id'); }); } public function GrandChild() { return $this->hasMany('App\Model\clients','under_reference','reference_id','id')->with("childs")->leftjoin('clients_payment_type',函数($join) { $join->on('clients_payment_type.user_id', '=', 'clients.id'); }); }
  • i.stack.imgur.com/mR869.png 数据库结构图片

标签: laravel laravel-5 eloquent treeview eloquent-relationship


【解决方案1】:

如果您想分别获取两者,则:

$parentCats = DB::table('table_name')->whereNull("cat_parent_id")->pluck("cat_name");

$childCats = DB::table('table_name')->whereNotNull("cat_parent_id")->pluck("cat_name");

然后在视图文件中,你可以遍历这些数组

【讨论】:

  • 树结构基于具有三个级别的单亲,其中级别 1 包含作为参考的父 ID,级别 2 应该从级别 3 的所有父级中获取所有子级,但是什么我得到的是单独的父母和单独的孩子,但需要所有孩子在一个表中查看 public function childs() { return $this->hasMany('App\Model\clients','under_reference','reference_id', 'id')->leftjoin('clients_payment_type', function($join) { $join->on('clients_payment_type.user_id', '=', 'clients.id'); });}
【解决方案2】:
class Category extends Model
{
//relations
    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function parent()
    {
        return $this->belongsTo(self::class, 'cat_parent_id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function children()
    {
        return $this->hasMany(self::class, 'cat_parent_id');
    }

    public function scopeParentsOnly($query)
    {
        return $query->whereNull('cat_parent_id');
    }
}

现在你可以这样称呼它

$categories = Category::query()->parentsOnly()->with('children')->get();

您将只获得属性为children 的父类别,其中包含每个类别的子类别。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-09
    • 1970-01-01
    • 2018-06-03
    • 1970-01-01
    • 2013-02-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多