PurchaseGoodsCateRelate.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace addons\Purchase\common\models;
  3. use Yii;
  4. /**
  5. * This is the model class for table "{{%addons_purchase_goods_cate_relate}}".
  6. *
  7. * @property int $id
  8. * @property int|null $cate_id 分类id
  9. * @property int|null $goods_id 产品id
  10. * @property int $created_at 创建时间
  11. * @property int $updated_at 修改时间
  12. */
  13. class PurchaseGoodsCateRelate extends \common\models\base\BaseActiveRecord
  14. {
  15. /**
  16. * {@inheritdoc}
  17. */
  18. public static function tableName()
  19. {
  20. return '{{%addons_purchase_goods_cate_relate}}';
  21. }
  22. /**
  23. * {@inheritdoc}
  24. */
  25. public function rules()
  26. {
  27. return [
  28. [['cate_id', 'goods_id', 'created_at', 'updated_at'], 'integer'],
  29. ];
  30. }
  31. /**
  32. * {@inheritdoc}
  33. */
  34. public function attributeLabels()
  35. {
  36. return [
  37. 'id' => 'ID',
  38. 'cate_id' => '分类id',
  39. 'goods_id' => '产品id',
  40. 'created_at' => '创建时间',
  41. 'updated_at' => '修改时间',
  42. ];
  43. }
  44. /**
  45. * 商品分类关联保存数据
  46. *
  47. * @param integer $goods_id
  48. * @param array $cats 分类ID
  49. * @param string $type
  50. * @return boolean
  51. */
  52. public static function setData(int $goods_id, array $cats, string $type = 'single')
  53. {
  54. try {
  55. if ($goods_id && $cats) {
  56. $insert = [];
  57. $now = time();
  58. // 删除旧的分类
  59. self::deleteAll([
  60. 'and',
  61. ['goods_id' => $goods_id],
  62. ]);
  63. // 生成新分类数据
  64. $insert = array_map(function ($item) use ($now, $goods_id) {
  65. return [$goods_id, $item, $now, $now];
  66. }, $cats);
  67. $field = ['goods_id', 'cate_id', 'created_at', 'updated_at'];
  68. // 批量插入数据
  69. Yii::$app->db->createCommand()->batchInsert(self::tableName(), $field, $insert)->execute();
  70. }
  71. return true;
  72. } catch (\Exception $e) {
  73. self::$static_error = $e->getMessage();
  74. return false;
  75. }
  76. }
  77. }