belongsTo(TrafficPoolV2::class, 'poolId', 'id'); } /** * 关联来源记录 */ public function sources() { return $this->hasMany(TrafficPoolSource::class, 'poolCompanyId', 'id'); } /** * 关联标签记录 */ public function tags() { return $this->hasMany(TrafficPoolTag::class, 'poolCompanyId', 'id'); } /** * 关联行为记录 */ public function behaviors() { return $this->hasMany(TrafficPoolBehavior::class, 'poolCompanyId', 'id'); } /** * 关联分配记录 */ public function allotRecords() { return $this->hasMany(TrafficPoolAllotRecord::class, 'poolCompanyId', 'id'); } /** * 根据identifier和companyId查找或创建 * @param string $identifier * @param int $companyId * @param int $poolId * @param array $data * @return static */ public static function findOrCreateByIdentifierAndCompany(string $identifier, int $companyId, int $poolId, array $data = []) { $record = self::where('identifier', $identifier) ->where('companyId', $companyId) ->where('isDel', 0) ->find(); if (!$record) { $insertData = array_merge([ 'poolId' => $poolId, 'identifier' => $identifier, 'companyId' => $companyId, 'createTime' => time(), ], $data); $record = self::create($insertData); } return $record; } /** * 原子更新消息统计 * @param int $count 增加的消息数量 * @return bool */ public function incrementMsgCount(int $count = 1) { return Db::table($this->getTable()) ->where('id', $this->id) ->inc('totalMsgCount', $count) ->inc('rfmF', $count) ->update([ 'lastMsgTime' => time(), 'lastInteractTime' => time(), 'updateTime' => time() ]); } /** * 原子更新订单统计 * @param float $amount 订单金额 * @return bool */ public function incrementOrderStats(float $amount) { return Db::table($this->getTable()) ->where('id', $this->id) ->inc('totalOrderCount', 1) ->inc('totalOrderAmount', $amount) ->inc('rfmM', $amount) ->update([ 'lastOrderTime' => time(), 'lastInteractTime' => time(), 'updateTime' => time() ]); } /** * 计算RFM R值(最后互动距今天数) * @return int */ public function getRfmRAttr() { if (empty($this->lastInteractTime)) { return 9999; // 未互动过 } return (int) floor((time() - $this->lastInteractTime) / 86400); } /** * 获取自定义字段 * @param string $value * @return array */ public function getCustomFieldsAttr($value) { return $value ? json_decode($value, true) : []; } /** * 设置自定义字段 * @param array $value * @return string */ public function setCustomFieldsAttr($value) { return $value ? json_encode($value, JSON_UNESCAPED_UNICODE) : null; } }