Files
fdesk/app/crm/model/Customer.php
T
2025-09-03 16:10:36 +08:00

115 lines
2.8 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace app\crm\model;
use app\common\model\Country;
use app\crm\utils\Util;
use config\constants\Constants;
use DateTimeInterface;
use Illuminate\Support\Carbon;
use support\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use app\common\model\User;
class Customer extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'crm_customer';
/**
* The primary key associated with the table.
*
* @var string
*/
protected $primaryKey = 'id';
//设置黑名单
protected $guarded = ['id','created_at','updated_at'];
// 指定日期字段存储格式为时间戳
protected $dateFormat = 'U';
/**
* Indicates if the model should be timestamped.
*
* @var bool
*/
public $timestamps = true;
use SoftDeletes;
protected $dates = ['deleted_at'];
protected $casts = [
'updated_at' => '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');
}
}