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

100 lines
2.4 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. 'extends' => $product->extends,
  33. 'longitude' => $product->longitude,
  34. 'latitude' => $product->latitude,
  35. 'address' => $product->address,
  36. ]);
  37. //UPDATE agent_products ap
  38. //INNER JOIN products p ON ap.product_id=p.id AND ap.product_id>0
  39. //SET ap.latitude=p.latitude, ap.longitude=p.longitude, ap.address=p.address;
  40. /** 同步信息到代理商产品 END */
  41. if ($product->isDirty('status') && $product->status == ProductStatus::ON_SALE) {
  42. ProductSaved::dispatch($product);
  43. }
  44. });
  45. # 删除产品同步删除代理商产品
  46. static::deleted(function ($product) {
  47. AgentProduct::query()->where('product_id', $product->id)->delete();
  48. });
  49. }
  50. // 获取所有产品图片
  51. public function getPicturesAttribute($value): array
  52. {
  53. if (is_string($value)) {
  54. $value = $value ? json_decode($value, true) : [];
  55. }
  56. $this->append('picture');
  57. return $value ?? [];
  58. }
  59. // 获取第一张产品图片
  60. public function getPictureAttribute($value): string
  61. {
  62. return $this->pictures[0] ?? '';
  63. }
  64. public function setPicturesAttribute($value)
  65. {
  66. if (is_array($value)) {
  67. $this->attributes['pictures'] = json_encode(array_filter($value));
  68. }
  69. }
  70. public function supplier()
  71. {
  72. return $this->belongsTo(Supplier::class)->withTrashed();
  73. }
  74. public function category()
  75. {
  76. return $this->belongsTo(Category::class);
  77. }
  78. public function spec()
  79. {
  80. return $this->hasMany(ProductSpec::class);
  81. }
  82. public function diyForm()
  83. {
  84. return $this->belongsTo(DiyForm::class);
  85. }
  86. }