按父级排序Eloquent集合

时间:2018-07-17 09:37:07

标签: php laravel eloquent

这是我的标签表:

ALLOWED_HOSTS = ['t17.proxy-checks.com']

如何将每个标签放置在其父标签下的集合?我的意思是:

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

谢谢。

3 个答案:

答案 0 :(得分:3)

给出模型Item与其自身的关系:

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

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

答案 1 :(得分: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;
    }
}

它将以您提到的嵌套形式对Comment Collection进行排序 我在Comment模型中有一个方法:

/**
 * 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();
}

答案 2 :(得分:0)

尝试一下:

print coordinates

for book in coordinates.keys():
    for page, s in coordinates[book].iteritems():
        if s == sentence:
            print("Book:%s, page: %s, position: %s, vowel: %s, sentence: %s" % (book, page, location, letter, sentence))