'json', ]; public function getThumbAttribute($thumb) { return assertUrl($thumb); } public function comments() { return $this->hasMany(Comment::class); } public function category() { return $this->belongsTo(Category::class); } public function cars() { return $this->hasMany(Car::class); } public function users() { return $this->belongsToMany(User::class, 'likes_products')->withTimestamps(); } public function detail() { return $this->hasOne(ProductDetail::class); } public function orderDetail() { return $this->hasOne(orderDetail::class); } /** * 使用 uuid 注入 * * @return string */ public function getRouteKeyName() { return 'uuid'; } public function getViewCountAttribute() { $date = Carbon::today()->toDateString(); return $this->attributes['view_count'] + Cache::get($this->getViewCountKey($date), 0); } public function getViewCountKey($date) { return "moon:products_cache_{$date}:view_count_{$this->id}"; } public static function boot() { parent::boot(); // 自动生成商品的 uuid, 拼音 static::saving(function (Product $model) { if (is_null($model->uuid)) { $model->uuid = Uuid::uuid4()->toString(); } if (is_null($model->pinyin)) { /** * @var $pinyin Pinyin */ $pinyin = app(Pinyin::class); $model->pinyin = $pinyin->permalink($model->name); $model->first_pinyin = substr($model->pinyin, 0, 1); } if ($model->isDirty('first_pinyin')) { // 建立拼音表 ProductPinYin::query()->firstOrCreate(['pinyin' => $model->first_pinyin]); } if (self::$addToSearch) { try { $model->addToIndex($model->getSearchData()); } catch (\Exception $e) { } } }); static::deleted(function (Product $model) { // 没有这个拼音了,删去 if (Product::query()->where('first_pinyin', $model->first_pinyin)->doesntExist()) { ProductPinYin::query()->where('pinyin', $model->first_pinyin)->delete(); } if (self::$addToSearch) { try { $model->removeFromIndex(); } catch (\Exception $e) { } } }); // 从软删除中恢复 static::restored(function (Product $model) { // 建立拼音表 ProductPinYin::query()->firstOrCreate(['pinyin' => $model->first_pinyin]); if (self::$addToSearch) { try { $model->addToIndex($this->getSearchData()); } catch (\Exception $e) { } } }); } public function getSearchData() { $categoryName = $this->category->title ?? ''; $title = $this->name . ' ' . $this->title; $text = str_replace(["\t", "\r", "\n"], ['', '', ''], strip_tags($this->detail->content ?? '')); return [ 'id' => $this->id, 'title' => $title, 'body' => $text . ' ' . $categoryName ]; } public function getIndexName() { return 'product'; } public function getMappingProperties() { return [ 'id' => [ 'type' => 'integer' ], 'title' => [ 'type' => 'text', 'analyzer' => 'ik_max_word', 'search_analyzer' => 'ik_smart', 'index' => true, ], 'body' => [ 'type' => 'text', 'analyzer' => 'ik_max_word', 'search_analyzer' => 'ik_smart', 'index' => true, ] ]; } }