海南旅游SAAS
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

93 lines
2.0 KiB

4 years ago
4 years ago
4 years ago
  1. <?php
  2. namespace App\Models;
  3. use App\Common\ProductStatus;
  4. use App\Jobs\ProductSaved;
  5. use Illuminate\Database\Eloquent\Factories\HasFactory;
  6. use Illuminate\Database\Eloquent\SoftDeletes;
  7. /**
  8. * 供应商产品
  9. * Class Product
  10. * @package App\Models
  11. */
  12. class Product extends BaseModel
  13. {
  14. use HasFactory, SoftDeletes;
  15. protected $guarded = ['id']; //不允许编辑的字段
  16. protected $casts = ['extends' => 'json'];
  17. /**
  18. * 模型的 "booted" 方法
  19. * @return void
  20. */
  21. protected static function booted()
  22. {
  23. parent::booted();
  24. static::saved(function ($product) {
  25. /** 同步信息到代理商产品 START */
  26. AgentProduct::where(['type' => 0, 'product_id' => $product->id])
  27. ->update([
  28. 'title' => $product->title,
  29. 'know' => $product->know,
  30. 'content' => $product->content,
  31. 'pictures' => $product->pictures,
  32. ]);
  33. /** 同步信息到代理商产品 END */
  34. if ($product->isDirty('status') && $product->status == ProductStatus::ON_SALE) {
  35. ProductSaved::dispatch($product);
  36. }
  37. });
  38. # 删除产品同步删除代理商产品
  39. static::deleted(function ($product) {
  40. AgentProduct::query()->where('product_id', $product->id)->delete();
  41. });
  42. }
  43. // 获取所有产品图片
  44. public function getPicturesAttribute($value): array
  45. {
  46. if (is_string($value)) {
  47. $value = $value ? json_decode($value, true) : [];
  48. }
  49. $this->append('picture');
  50. return $value ?? [];
  51. }
  52. // 获取第一张产品图片
  53. public function getPictureAttribute($value): string
  54. {
  55. return $this->pictures[0] ?? '';
  56. }
  57. public function setPicturesAttribute($value)
  58. {
  59. if (is_array($value)) {
  60. $this->attributes['pictures'] = json_encode(array_filter($value));
  61. }
  62. }
  63. public function supplier()
  64. {
  65. return $this->belongsTo(Supplier::class)->withTrashed();
  66. }
  67. public function category()
  68. {
  69. return $this->belongsTo(Category::class);
  70. }
  71. public function spec()
  72. {
  73. return $this->hasMany(ProductSpec::class);
  74. }
  75. public function diyForm()
  76. {
  77. return $this->belongsTo(DiyForm::class);
  78. }
  79. }