php - Laravel Get all child node count with condition -
i using laravel5.1 in application. in have 1 table name users , schema of user table follow.
id name parane_id node 1 abc 0 2 xyz 1 l 3 dfs 1 r 4 gjk 2 l 5 dsg 3 l 6 faf 4 r 7 kes 2 r
i want count of user left side on user 1 (i.e 2,4,6,7) count 4.
same if want right side of 2 return 7 count 1.
how can possible using laravel eloquent
.
any appreciated.
you want count tree nodes on condition in case left children of node.
define children user
. create function traverse children tree , counting.
class user extends model { public function children() { return $this->hasmany('app\user', 'parent_id'); } public function countchildren($node = null) { $query = $this->children(); if (!empty($node)) { $query = $query->where('node', $node); } $count = 0; foreach ($query->get() $child) { $count += $child->countchildren() + 1; // plus 1 count direct child } return $count; } }
to count left children of user id 1.
$user = user::find(1); $count = $user->countchildren('l');
Comments
Post a Comment