BatchProvider.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: sunmoon<i@liming.me>
  5. * Date: 2019/07/29
  6. * Time: 上午9:39
  7. */
  8. namespace common\libs\logging\operate\provider;
  9. class BatchProvider extends AbstractProvider {
  10. /**
  11. * 格式化 sql 中的 in
  12. * @param array $array
  13. * @return string
  14. */
  15. public static function staticFormatIn(array $array){
  16. $array = array_unique($array);
  17. $in = "'" . implode("','", $array) . "'";
  18. return $in;
  19. }
  20. /**
  21. * 标准化
  22. * @param $data
  23. * @return array|bool
  24. */
  25. public function normalize($data){
  26. if(!$data){
  27. return false;
  28. }
  29. if(!$this->getLabels()){
  30. return false;
  31. }
  32. $result = [];
  33. foreach($data as $key => $value){
  34. if(!isset($this->attrLabels[$key])) continue;
  35. if($this->needCompose($this->attrLabels[$key])){
  36. $value = [$value];
  37. foreach($this->attrLabels[$key]['compose'] as $field){
  38. if(isset($data[$field])){
  39. $value[] = $data[$field];
  40. }
  41. }
  42. }
  43. $result[$key] = $this->handleData($this->attrLabels[$key], $value);
  44. }
  45. return $result;
  46. }
  47. /**
  48. * 批量获取数据
  49. */
  50. public function batchGetData(){
  51. if(!$this->data){
  52. return ;
  53. }
  54. $this->data = array_unique($this->data);
  55. $ids = self::staticFormatIn($this->data);
  56. $fetchClass = $this->fetchClass;
  57. if($this->select){
  58. $list = $fetchClass::find()->select($this->select)->where("{$this->dataType} IN (".$ids.")")->indexBy($this->dataType)->asArray()->all();
  59. }else{
  60. $list = $fetchClass::find()->selectNoText()->where("{$this->dataType} IN (".$ids.")")->indexBy($this->dataType)->asArray()->all();
  61. }
  62. $this->result = [];
  63. if($list){
  64. foreach($this->data as $id){
  65. if(isset($list[$id])){
  66. $this->result[$id] = $this->normalize($list[$id]);
  67. }
  68. }
  69. }
  70. }
  71. public function beforeDelete(){
  72. $this->batchGetData();
  73. }
  74. public function beforeUpdate(){
  75. $this->batchGetData();
  76. }
  77. public function afterUpdate(){
  78. $this->batchGetData();
  79. }
  80. }