Laravel查询生成器以获取递归结果?例如. id,parent_id [英] Laravel query builder for recursive results? E.g. id, parent_id

查看:570
本文介绍了Laravel查询生成器以获取递归结果?例如. id,parent_id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我的数据结构如下:

So I have data structured like this:

id|parent_id|name
1 |null     |foo
2 |1        |bar
3 |2        |baz

所以基本上是foo->bar->baz.我很困惑如何使用laravel的查询生成器来获取子行的行,然后获取其祖先的行(直到parent_id == null). laravel能做到吗?我进行了一些研究,Postgres使用了RECURSIVE,而MySQL没有使用(c2>(

So basically foo->bar->baz. I'm stumped on how to use laravel's query builder to get rows for a child row, then its ancestors (until parent_id == null). Can this be done with laravel? I've done a little research and Postgres has RECURSIVE while MySQL doesn't (Postgres recursive query to update values of a field while traversing parent_id).

我相信MySQL具有类似的功能:如何做到MySQL中的递归SELECT查询?

I believe MySQL has something similar: How to do the Recursive SELECT query in MySQL?

但是我该如何在Laravel中实现呢?

But how would I implement this in Laravel?

我的起始代码基本上是使用查询范围,但我只是做得不好:

My starting code is basically using a query scope, but I'm just not getting it right:

Model::select('name')->getParent(3); //get baz and the ancestors of baz
protected function scopeGetParent($id) {
  $parent = Model::where('id', '=', $id);
  return $query->getParent($parent->parent_id);
}

我想要的理想结果是:

name
baz
bar
foo

有什么想法吗?

推荐答案

所以在摆弄Collections类的merge()方法之后:

So after fiddling around with the merge() method for the Collections class:

public static function ancestors($id)
{
    $ancestors = Model::where('id', '=', $id)->get();

    while ($ancestors->last()->parent_id !== null)
    {
      $parent = Model::where('id', '=', $ancestors->last()->parent_id)->get();
      $ancestors = $ancestors->merge($parent);
    }

    return $ancestors;
}

这将产生我所需要的,但是我相信它可以更清洁,所以请随时对其进行编辑!

That will produce what I needed, however I believe it can be more cleaner so please feel free to edit it!

这篇关于Laravel查询生成器以获取递归结果?例如. id,parent_id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆