hasMany(TrafficPoolGroupMember::class, 'groupId', 'id'); } /** * 获取规则配置 * @param string $value * @return array|null */ public function getRuleConfigAttr($value) { return $value ? json_decode($value, true) : null; } /** * 设置规则配置 * @param array $value * @return string */ public function setRuleConfigAttr($value) { return $value ? json_encode($value, JSON_UNESCAPED_UNICODE) : null; } /** * 获取公司可用的分组列表(包含系统分组和公司自定义分组) * @param int $companyId * @param bool $onlyEnabled * @return \think\Collection */ public static function getGroupsByCompany(int $companyId, bool $onlyEnabled = true) { $query = self::whereIn('companyId', [0, $companyId]) ->where('isDel', 0); if ($onlyEnabled) { $query->where('status', self::STATUS_ENABLED); } return $query->order('sort ASC, id ASC')->select(); } /** * 根据分组编码获取分组 * @param string $groupCode * @param int $companyId * @return static|null */ public static function getByCode(string $groupCode, int $companyId = 0) { return self::where('groupCode', $groupCode) ->whereIn('companyId', [0, $companyId]) ->where('isDel', 0) ->find(); } /** * 解析规则配置生成SQL条件 * @param array $ruleConfig * @return array [whereConditions, bindings] */ public static function parseRuleToConditions(array $ruleConfig) { $conditions = []; $bindings = []; if (empty($ruleConfig['conditions'])) { return [$conditions, $bindings]; } $logic = strtoupper($ruleConfig['logic'] ?? 'AND'); foreach ($ruleConfig['conditions'] as $condition) { if ($condition['type'] === 'group') { // 嵌套分组,递归处理 [$subConditions, $subBindings] = self::parseRuleToConditions($condition); if (!empty($subConditions)) { $conditions[] = '(' . implode(' ' . ($condition['logic'] ?? 'AND') . ' ', $subConditions) . ')'; $bindings = array_merge($bindings, $subBindings); } } elseif ($condition['type'] === 'field') { // 字段条件 $field = $condition['field']; $operator = $condition['operator']; $value = $condition['value']; switch ($operator) { case '=': case '!=': case '>': case '<': case '>=': case '<=': $conditions[] = "`{$field}` {$operator} ?"; $bindings[] = $value; break; case 'in': $placeholders = implode(',', array_fill(0, count($value), '?')); $conditions[] = "`{$field}` IN ({$placeholders})"; $bindings = array_merge($bindings, $value); break; case 'not_in': $placeholders = implode(',', array_fill(0, count($value), '?')); $conditions[] = "`{$field}` NOT IN ({$placeholders})"; $bindings = array_merge($bindings, $value); break; case 'between': $conditions[] = "`{$field}` BETWEEN ? AND ?"; $bindings[] = $value[0]; $bindings[] = $value[1]; break; case 'like': $conditions[] = "`{$field}` LIKE ?"; $bindings[] = '%' . $value . '%'; break; } } elseif ($condition['type'] === 'tag') { // 标签条件需要特殊处理,通过子查询 // 这里返回需要在Service层特殊处理 $conditions[] = "EXISTS (SELECT 1 FROM ck_traffic_pool_tag tpt WHERE tpt.poolCompanyId = ck_traffic_pool_company.id AND tpt.tagName IN (?))"; $bindings[] = implode("','", $condition['value']); } } return [$conditions, $bindings, $logic]; } }