php - MySQL - order/group records by foreign key referencing the same table (Laravel, ORM) -
i making application in laravel, , have run problem. creating simple crud back-end manage pages. page table structure (simplified) follows:
id | title | parent_id ----------------------------- 1 | homepage | 0 2 | | 0 3 | team | 2 4 | mission | 2 5 | directors| 3 6 | contact | 0
in application, want display records nested parents. this:
homepage - team - directors - mission contact
i able in normal application. however, need query/methods work eloquent
models arranges in order. nesting not necessary, can make checks per individual record, however, need query return pages in order per above.
this code, while groups correctly pages same parents, need query put them in correct place, order below parent page:
page::orderby('parent_id')->get();
thanks help!
first of all, define @ model relationship itself, this:
public function children() { return $this->hasmany('app\page', 'parent_id', 'id'); }
next, can retrieve first level items follows children:
page::with('children.children.children')->where('parent_id', 0)->get();
Comments
Post a Comment