海南旅游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.

88 lines
1.9 KiB

4 years ago
5 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. // 获取所有产品图片
  40. public function getPicturesAttribute($value): array
  41. {
  42. if (is_string($value)) {
  43. $value = $value ? json_decode($value, true) : [];
  44. }
  45. $this->append('picture');
  46. return $value ?? [];
  47. }
  48. // 获取第一张产品图片
  49. public function getPictureAttribute($value): string
  50. {
  51. return $this->pictures[0] ?? '';
  52. }
  53. public function setPicturesAttribute($value)
  54. {
  55. if (is_array($value)) {
  56. $this->attributes['pictures'] = json_encode(array_filter($value));
  57. }
  58. }
  59. public function supplier()
  60. {
  61. return $this->belongsTo(Supplier::class)->withTrashed();
  62. }
  63. public function category()
  64. {
  65. return $this->belongsTo(Category::class);
  66. }
  67. public function spec()
  68. {
  69. return $this->hasMany(ProductSpec::class);
  70. }
  71. public function diyForm()
  72. {
  73. return $this->belongsTo(DiyForm::class);
  74. }
  75. }