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

78 lines
1.6 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. if ($product->isDirty('status') && $product->status == ProductStatus::ON_SALE) {
  26. ProductSaved::dispatch($product);
  27. }
  28. });
  29. }
  30. // 获取所有产品图片
  31. public function getPicturesAttribute($value): array
  32. {
  33. if (is_string($value)) {
  34. $value = $value ? json_decode($value, true) : [];
  35. }
  36. $this->append('picture');
  37. return $value ?? [];
  38. }
  39. // 获取第一张产品图片
  40. public function getPictureAttribute($value): string
  41. {
  42. return $this->pictures[0] ?? '';
  43. }
  44. public function setPicturesAttribute($value)
  45. {
  46. if (is_array($value)) {
  47. $this->attributes['pictures'] = json_encode(array_filter($value));
  48. }
  49. }
  50. public function supplier()
  51. {
  52. return $this->belongsTo(Supplier::class)->withTrashed();
  53. }
  54. public function category()
  55. {
  56. return $this->belongsTo(Category::class);
  57. }
  58. public function spec()
  59. {
  60. return $this->hasMany(ProductSpec::class);
  61. }
  62. public function diyForm()
  63. {
  64. return $this->belongsTo(DiyForm::class);
  65. }
  66. }