php分销关系实现
PHP分销关系实现
分销系统的核心在于建立多级用户关系链,并通过佣金计算实现利益分配。以下是基于PHP的实现方案:
数据库设计
用户表需包含分销关系字段:
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`parent_id` int(11) DEFAULT NULL COMMENT '上级ID',
`level` tinyint(4) DEFAULT 0 COMMENT '分销层级',
`path` varchar(255) DEFAULT NULL COMMENT '关系路径(如:1,3,5)',
PRIMARY KEY (`id`),
INDEX `parent_id` (`parent_id`)
);
订单表需记录分佣信息:
CREATE TABLE `orders` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`amount` decimal(10,2) NOT NULL,
`commission_status` tinyint(1) DEFAULT 0,
PRIMARY KEY (`id`)
);
佣金记录表:
CREATE TABLE `commissions` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`order_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`level` tinyint(4) NOT NULL COMMENT '分销层级',
`amount` decimal(10,2) NOT NULL,
`create_time` datetime NOT NULL,
PRIMARY KEY (`id`)
);
关系链建立
用户注册时绑定上级关系:
function registerUser($username, $parentId = 0) {
$parentPath = '';
if ($parentId > 0) {
$parent = $db->query("SELECT path FROM users WHERE id = $parentId");
$parentPath = $parent['path'] ? $parent['path'].','.$parentId : $parentId;
}
$level = $parentPath ? count(explode(',', $parentPath)) : 0;
$db->insert('users', [
'username' => $username,
'parent_id' => $parentId,
'level' => $level,
'path' => $parentPath
]);
}
佣金计算逻辑
订单支付成功后触发分佣:
function handleCommission($orderId) {
$order = $db->query("SELECT * FROM orders WHERE id = $orderId");
$user = $db->query("SELECT path FROM users WHERE id = {$order['user_id']}");
if (empty($user['path'])) return;
$parentIds = explode(',', $user['path']);
$commissionRules = [
1 => 0.10, // 一级分佣10%
2 => 0.05, // 二级分佣5%
3 => 0.02 // 三级分佣2%
];
foreach ($parentIds as $level => $parentId) {
$currentLevel = $level + 1;
if (!isset($commissionRules[$currentLevel])) continue;
$commission = $order['amount'] * $commissionRules[$currentLevel];
$db->insert('commissions', [
'order_id' => $orderId,
'user_id' => $parentId,
'level' => $currentLevel,
'amount' => $commission,
'create_time' => date('Y-m-d H:i:s')
]);
}
$db->update('orders', ['commission_status' => 1], "id = $orderId");
}
性能优化方案
使用闭包表存储关系:
CREATE TABLE `user_relations` (
`ancestor` int(11) NOT NULL,
`descendant` int(11) NOT NULL,
`depth` int(11) NOT NULL,
PRIMARY KEY (`ancestor`,`descendant`)
);
批量插入关系数据:
function rebuildRelationTree() {
$db->query("TRUNCATE user_relations");
$users = $db->queryAll("SELECT id, path FROM users");
foreach ($users as $user) {
if (empty($user['path'])) continue;
$pathIds = explode(',', $user['path']);
foreach ($pathIds as $depth => $ancestorId) {
$db->insert('user_relations', [
'ancestor' => $ancestorId,
'descendant' => $user['id'],
'depth' => $depth + 1
]);
}
}
}
安全注意事项
- 防止循环引用:在绑定上级时检查关系链是否形成闭环
- 佣金提现需进行人工审核
- 敏感操作记录日志
- 定期备份关系数据
实现时可根据业务需求调整分佣层级比例,建议结合缓存机制优化关系查询性能。对于大规模用户体系,考虑使用图数据库处理复杂关系网络。







