id,ancestor,descendant,lvl,tier_id
1, 11, 11, 0, 0
2, 11, 65, 1, 1
3, 65, 65, 0, 0
5, 11, 66, 1, 2
6, 66, 66, 0, 0
i am using closure table model. i placed tier_id cloumn there.
let say new entry save in above table then tier_id should be placed like 1,2,3
if any previous ancestor exist then it should check in table and if tier_id reaches 3 then it will store 3 and if any new ancestor entry occure then it will store 1,2,3 accordingly.
for achiveing i made a function generate_tier($node_id) and passing $node_id to it. but when i am seeing result array it will incrementing previous tier_id.
when there is only one entry in table.
Array
(
[0] => Array
(
[name] => Shri ram
[affiliate_id] => 597612
[id] => 65
[parent] => 11
[level] => 1
[tier_id] => 1
)
)
after second record entry. id--> 65 tier_id-->2
Array
(
[0] => Array
(
[name] => Shri ram
[affiliate_id] => 597612
[id] => 65
[parent] => 11
[level] => 1
[tier_id] => 2
)
[1] => Array
(
[name] => Ravi
[affiliate_id] => 831375
[id] => 66
[parent] => 11
[level] => 1
[tier_id] => 1
)
)
/**
* Add a node (as last child).
*
* @param int node id
* @param int target id
* @return boolean
*/
public function add($node_id, $target_id = 0) {
$sql = 'SELECT ancestor, ' . $node_id . ', lvl+1
FROM ' . $this->closure_table . '
WHERE descendant = ' . $target_id . '
UNION
SELECT ' . $node_id . ',' . $node_id . ',0';
//original $query = 'INSERT INTO '.$this->closure_table.' (ancestor, descendant,lvl) ('.$sql.')';
$query = 'INSERT INTO ' . $this->closure_table . ' (ancestor, descendant,lvl) ' . $sql . '';
$result = $this->db->query($query);
return $result;
}
public function generate_tier($node_id) {
$sql = 'select id,tier_id from cbf_affiliate_chain_closers where ancestor=' . $node_id . ' and descendant <> ' . $node_id . '';
$query = $this->db->query($sql);
$result_arr=$query->result();
if (count($result_arr) > 0) {
foreach ($result_arr as $row) {
$previous_tier = $row->tier_id;
if ($previous_tier == 3) {
$data = array(
'tier_id' => 3,
);
} else {
$data = array(
'tier_id' => $row->tier_id + 1,
);
}
$this->db->where('id', $row->id);
$this->db->update($this->closure_table, $data);
}
}
}