Files
fdesk/app/crm/model/Customer.php
T

109 lines
2.6 KiB
PHP
Raw Normal View History

2025-07-09 15:10:14 +08:00
<?php
namespace app\crm\model;
use app\crm\utils\Util;
use config\constants\Constants;
use DateTimeInterface;
use Illuminate\Support\Carbon;
use support\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
2025-07-15 09:39:02 +08:00
use app\common\model\User;
2025-07-09 15:10:14 +08:00
class Customer extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
2025-07-10 14:27:56 +08:00
protected $table = 'crm_customer';
2025-07-09 15:10:14 +08:00
/**
* 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()
{
2025-07-15 13:52:31 +08:00
return $this->belongsToMany(Tag::class, 'crm_customer_tag', 'customer_id', 'tag_id')
2025-07-09 15:10:14 +08:00
->withTimestamps(); // 如果需要记录关联时间
}
// 定义与 变更历史 的一对多关系
public function his()
{
return $this->hasMany(CustomerHis::class, 'customer_id', 'id');
}
// 定义反向多对一关联
public function user()
{
return $this->belongsTo(User::class, 'user_id', 'id');
}
2025-08-14 20:08:57 +08:00
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);
});
}
2025-07-09 15:10:14 +08:00
}