belongsTo('User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0); } /** * 关联身体测量数据 */ public function measurements() { return $this->hasMany('BodyMeasurements', 'profile_id', 'id'); } /** * 关联最新的身体测量数据 */ public function latestMeasurement() { return $this->hasOne('BodyMeasurements', 'profile_id', 'id')->order('measurement_date DESC'); } /** * 关联身体类型选择 */ public function bodyTypeSelections() { return $this->hasMany('BodyTypeSelection', 'profile_id', 'id'); } /** * 关联AI报告 */ public function aiReports() { return $this->hasMany('BodyAiReport', 'profile_id', 'id'); } /** * 关联最新AI报告 */ public function latestAiReport() { return $this->hasOne('BodyAiReport', 'profile_id', 'id')->order('generated_time DESC'); } /** * 获取性别文本 */ public function getGenderTextAttr($value, $data) { $genderMap = [ 1 => '男', 2 => '女' ]; return isset($genderMap[$data['gender']]) ? $genderMap[$data['gender']] : '未知'; } /** * 获取是否本人档案文本 */ public function getIsOwnTextAttr($value, $data) { return $data['is_own'] ? '本人档案' : '他人档案'; } /** * 获取身体照片数组 */ public function getBodyPhotosTextAttr($value, $data) { if (empty($data['body_photos'])) { return [ 'front' => '', 'side' => '', 'back' => '' ]; } return json_decode($data['body_photos'], true); } /** * 设置身体照片 */ public function setBodyPhotosAttr($value) { return is_array($value) ? json_encode($value) : $value; } /** * 获取完整的档案信息(包含测量数据和体型选择) */ public function getFullProfileData() { $profile = $this->toArray(); // 获取最新测量数据 $latestMeasurement = $this->latestMeasurement; $profile['measurements'] = $latestMeasurement ? $latestMeasurement->toArray() : null; // 获取体型选择 $bodyTypes = $this->bodyTypeSelections()->with('typeConfig')->select(); $profile['body_types'] = []; foreach ($bodyTypes as $selection) { $profile['body_types'][$selection['type_category']] = [ 'type_id' => $selection['selected_type_id'], 'type_name' => $selection->typeConfig ? $selection->typeConfig['type_name'] : '', 'type_image' => $selection->typeConfig ? cdnurl($selection->typeConfig['type_image'], true) : '' ]; } // 获取最新AI报告 $latestReport = $this->latestAiReport; $profile['ai_report'] = $latestReport ? $latestReport->toArray() : null; return $profile; } /** * 计算BMI指数 */ public function calculateBMI() { if ($this->height <= 0 || $this->weight <= 0) { return 0; } $heightInMeters = $this->height / 100; return round($this->weight / ($heightInMeters * $heightInMeters), 2); } /** * 获取BMI等级 */ public function getBMILevel() { $bmi = $this->calculateBMI(); if ($bmi < 18.5) { return '偏瘦'; } elseif ($bmi < 24) { return '正常'; } elseif ($bmi < 28) { return '超重'; } else { return '肥胖'; } } }