Laravel查询生成器以获取递归结果?例如. id,parent

编程入门 行业动态 更新时间:2024-10-07 18:30:10
本文介绍了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>( Postgres递归查询,用于遍历parent_id时更新字段的值).

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

本文发布于:2023-10-23 02:28:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1519472.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   生成器   Laravel   id   parent

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!