按其父级对Eloquent集合进行排序

4
这是我的标签表格:
id      name        parent
--------------------------
1      parent1      null
2      a            parent1
3      b            parent1
4      parent2      null
5      c            parent2
6      d            parent1
7      parent3      null
8      e            parent3
9      f            parent2

我应该如何创建一个集合,让每个标签都放在它的父标签下面?我的意思是:

Collection {#499 ▼
  #items: array:22 [▼
    0 => tag {#524 ▶} //parent1
    1 => tag {#525 ▶} //a
    2 => tag {#526 ▶} //b
    3 => tag {#527 ▶} //d
    4 => tag {#528 ▶} //parent2
    5 => tag {#529 ▶} //c
    6 => tag {#530 ▶} //f
    7 => tag {#530 ▶} //parent3
    8 => tag {#530 ▶} //e
  ]
}

thanks.

3个回答

4

假设有一个名为 Item 的模型,它与自身相关联:

class Item extends model {
    public function children() {
         // parent being a foreign key
         return $this->hasMany(__CLASS__, 'parent', 'id');
    }
}

$items = Item::with('children')->get();

0
你需要创建自定义集合类来完成这个任务,以下是一个示例代码:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Collection;

/**
 * Class CommentCollection
 * @package App
 */
class CommentCollection extends Collection {

    /**
     * @return Collection
     */
    public function threaded()
    {
        $comments = parent::groupBy('parent_id');

        if (count($comments))
        {
            $comments['root'] = $comments[0];
            unset($comments[0]);
        }

        return $comments;
    }
}

它将按照你提到的方式对评论集合进行嵌套形式的排序。 我在评论模型中有一个方法:

/**
 * Use a custom collection for all comments.
 *
 * @param  array $models
 *
 * @return CommentCollection
 */
public function newCollection(array $models = [])
{
    return new CommentCollection($models);
}

我还有一个针对Post模型的方法:

/**
 * @return mixed
 */
public function getThreadedComments()
{
    return $this->comments()->with('owner')->where('verified', '=', TRUE)->get()->threaded();
}

0

试试这个:

class Example extends model {
    public function children() {
         return $this->hasMany( __CLASS__ , 'parent', 'id');
                }
            }
$data = Example::with('children')->latest();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接