ServiceRel.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2021 https://www.yiovo.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
  8. // +----------------------------------------------------------------------
  9. // | Author: 萤火科技 <admin@yiovo.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types = 1);
  12. namespace app\store\model\goods;
  13. use app\common\model\goods\ServiceRel as ServiceRelModel;
  14. /**
  15. * 商品服务与承诺模型
  16. * Class ServiceRel
  17. */
  18. class ServiceRel extends ServiceRelModel
  19. {
  20. /**
  21. * 根据服务ID获取记录总数量
  22. * @param int $serviceId
  23. * @return int
  24. */
  25. public static function getCountByServiceId(int $serviceId)
  26. {
  27. return (new static)->where('service_id', '=', $serviceId)->count();
  28. }
  29. /**
  30. * 批量写入商品服务记录
  31. * @param int $goodsId
  32. * @param array $serviceIds
  33. * @return array|false
  34. */
  35. public static function increased(int $goodsId, array $serviceIds)
  36. {
  37. $dataset = [];
  38. foreach ($serviceIds as $serviceId) {
  39. $dataset[] = [
  40. 'service_id' => $serviceId,
  41. 'goods_id' => $goodsId,
  42. 'store_id' => self::$storeId
  43. ];
  44. }
  45. return (new static)->addAll($dataset);
  46. }
  47. /**
  48. * 更新关系记录
  49. * @param $goodsId
  50. * @param array $serviceIds 新的服务集
  51. * @return array|false
  52. * @throws \Exception
  53. */
  54. public static function updates(int $goodsId, array $serviceIds)
  55. {
  56. // 已分配的服务集
  57. $assignServiceIds = self::getServiceIds($goodsId);
  58. // 找出删除的服务
  59. $deleteServiceIds = array_diff($assignServiceIds, $serviceIds);
  60. if (!empty($deleteServiceIds)) {
  61. static::deleteAll([
  62. ['goods_id', '=', $goodsId],
  63. ['service_id', 'in', $deleteServiceIds]
  64. ]);
  65. }
  66. // 找出添加的服务
  67. $newServiceIds = array_diff($serviceIds, $assignServiceIds);
  68. $dataset = [];
  69. foreach ($newServiceIds as $serviceId) {
  70. $dataset[] = [
  71. 'goods_id' => $goodsId,
  72. 'service_id' => $serviceId,
  73. 'store_id' => self::$storeId,
  74. ];
  75. }
  76. return (new static)->addAll($dataset);
  77. }
  78. }