所以我的数据结构如下:
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
发布评论