【问题标题】:Laravel Elloquent, Sort relation to make it treeLaravel Eloquent,排序关系使其成为树
【发布时间】:2018-02-23 16:30:57
【问题描述】:

我想根据第二层 elloquent 关系生成树

我有 3 张桌子:

用户(ID、姓名)

帖子(id、parent_id、姓名)

类别(user_id,post_id)

我有如下示例表:

用户

标识 |名字

1 |约翰·多伊

发帖

标识 | parent_id |名字

1 | 0 |邮政A

2 | 1 |发布 A.1

3 | 4 |发布 B.1

4 | 0 |发布 B

类别

user_id | post_id

1 | 1

1 | 2

1 | 3

1 | 4

我的问题是,如何对用户的帖子进行排序以获取树?

@foreach($user->categories as $category)

  {{$category->post->name}}

@endfor

我希望结果是:

  • 邮递

  • 发布 A.1

  • 帖子 B(不是帖子 B.1)

  • 发布 B.1

谢谢你,我真的不知道如何解决这个问题..

【问题讨论】:

  • 你有什么模型实现了吗?
  • 如何在控制器中获取查询?

标签: laravel eloquent relation laravel-eloquent


【解决方案1】:

一种可能的智能解决方案(以及其他任何解决方案,例如从数据库中过滤)可能只是对 $user->categories 结果集合进行排序。 Eloquent 集合对此有一个方法:

@foreach($user->categories->sortBy('name') as $category)

官方文档链接: https://laravel.com/docs/5.6/collections#method-sortby

干杯。

【讨论】:

    【解决方案2】:

    您已经以非常规的方式命名了您的数据透视表,但此代码将对您有所帮助。 首先尝试将子关系添加到您的 post 模型中:

    public function children()
    {
        return $this->hasMany(Post::class,'parent_id','id');
    }
    

    这种实用方法适用于具有 n 个子项的 n 个类别

    首先创建一个局部视图category.blade.php 文件,该文件会递归调用自身来加载其子项

    <li>
       @if ($category->post->children()->count() > 0 )
           <ul>
               @foreach($category->post->->children as $category)
    
                       @include('category', $category) //the magic is in here
    
               @endforeach
           </ul>
       @endif
    </li>
    

    然后在主视图中添加此代码以递归方式加载所有子视图

    <ul>
        @foreach ($user->categories as $category)
    
            @if($category->post->parent_id == 0 )
    
                @include('category', $category)
    
            @endif
    
        @endforeach
    </ul>
    

    【讨论】:

    • 哇,我认为这可能是解决方案.. 非常感谢,它救了我!
    猜你喜欢
    • 2017-08-22
    • 2015-07-05
    • 2017-07-12
    • 2021-01-25
    • 2014-06-25
    • 2021-07-14
    • 2015-03-27
    • 2017-10-28
    • 1970-01-01
    相关资源
    最近更新 更多