'datetime:Y-m-d H:i:s', // 指定序列化格式 'created_at' => 'datetime:Y-m-d H:i:s', // 指定序列化格式 ]; /** * 重新格式化时间 * @param DateTimeInterface $date * @return string */ protected function serializeDate(DateTimeInterface $date): string { return $date->format(Carbon::parse($date)->toDateTimeString()); } /** * 客户的标签 */ public function tags() { return $this->belongsToMany(Tag::class, 'crm_customer_tag', 'customer_id', 'tag_id') ->withTimestamps(); // 如果需要记录关联时间 } // 定义与 变更历史 的一对多关系 public function his() { return $this->hasMany(CustomerHis::class, 'customer_id', 'id'); } // 定义反向多对一关联 public function user() { return $this->belongsTo(User::class, 'user_id', 'id'); } protected static function booted() { static::saved(function ($customer) { if (empty($customer->code)) { $customer->code = self::generateCustomerCode($customer); // 使用saveQuietly避免递归调用 $customer->saveQuietly(); } }); } public static function generateCustomerCode($customer) { // 生成唯一16位code,CM+14位 $unique = strtoupper(substr(md5($customer->id . microtime(true) . mt_rand(1000, 9999)), 8, 6)); $code = 'CM' . date('Ymd') .$unique; return $code; } // 静默保存方法,不触发事件 public function saveQuietly(array $options = []) { return static::withoutEvents(function () use ($options) { return $this->save($options); }); } public function countryInfo() { return $this->hasOne(Country::class, 'id', 'country_id'); } }