嗨,我的数据库设计为
+-------------+--------------+-------+
| referral_id | referrent_id | level |
+-------------+--------------+-------+
在我的数据库中,我有一排这样的数据:
+---+---+---+
| 1 | 1 | 0 |
+---+---+---+
| 1 | 2 | 1 |
+---+---+---+
| 1 | 3 | 1 |
+---+---+---+
| 1 | 4 | 1 |
+---+---+---+
| 2 | 2 | 0 |
+---+---+---+
| 3 | 3 | 0 |
+---+---+---+
| 4 | 4 | 0 |
+---+---+---+
基本上树是
/ 2
1 - 3
\ 4
我正在尝试将3降低到2以下
/ 2 - 3
1 - 4
我的实现:
public function changeReferrer(Member $newReferrer) {
$oldReferrer = $this->getReferrer(1); // this retrieves the ancestor one level up
DB::select('DELETE a FROM Referrer_Referent AS a
JOIN Referrer_Referent as d ON a.referent_id = d.referent_id
LEFT JOIN Referrer_Referent AS x
ON x.referrer_id = d.referrer_id AND x.referent_id = a.referrer_id
WHERE d.referrer_id = '.$oldReferrer->id.'
AND x.referrer_id IS NULL');
DB::select('INSERT into Referrer_Referent (referrer_id, referent_id, level)
SELECT supertree.referrer_id, subtree.referent_id, supertree.level + subtree.level + 1
FROM Referrer_Referent as supertree JOIN Referrer_Referent as subtree
WHERE subtree.referrer_id = '.$oldReferrer->id.'
AND supertree.referent_id = '.$newReferrer->id);
}
所以我将函数称为$user3->changeReferrer($user2);
,但出现这些错误:
违反完整性约束:1062键“ PRIMARY”的重复条目“ 1-1”(SQL:插入Referrer_Referent(referrer_id,referent_id,级别)SELECT SELECT supertree.referrer_id,subtree.referent_id,supertree.level + subtree.level + 1 FROM Referrer_Referent作为父树JOIN Referrer_Referent作为子树WHERE subtree.referrer_id = 1 AND supertree.referent_id = 2)
将此blog作为参考。