SearchModel.php 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. <?php
  2. namespace common\models\base;
  3. use yii\base\Model;
  4. use yii\data\ActiveDataProvider;
  5. use yii\data\Pagination;
  6. use yii\db\ActiveQuery;
  7. use yii\web\NotFoundHttpException;
  8. /**
  9. * // 示例一
  10. *
  11. * ```php
  12. * $searchModel = new SearchModel(
  13. * [
  14. * 'model' => Topic::class,
  15. * 'scenario' => 'default',
  16. * ]
  17. * );
  18. *
  19. * $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
  20. *
  21. * return $this->render('index', [
  22. * 'dataProvider' => $dataProvider,
  23. * ]);
  24. * ```
  25. *
  26. * // 示例二
  27. *
  28. *```php
  29. * $searchModel = new SearchModel(
  30. * [
  31. * 'defaultOrder' => ['id' => SORT_DESC],
  32. * 'model' => Topic::class,
  33. * 'scenario' => 'default',
  34. * 'relations' => ['comment' => []], // 关联表(可以是Model里面的关联)
  35. * 'partialMatchAttributes' => ['title'], // 模糊查询
  36. * 'pageSize' => 15
  37. * ]
  38. * );
  39. *
  40. * $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
  41. * $dataProvider->query->andWhere([Topic::tableName() . '.user_id' => 23, Comment::tableName() . '.status' => 1]);
  42. *
  43. * return $this->render('index', [
  44. * 'dataProvider' => $dataProvider,
  45. * ]);
  46. * ```
  47. *
  48. * Class SearchModel
  49. * @package common\components
  50. * @property \yii\db\ActiveRecord|\yii\base\Model $model
  51. */
  52. class SearchModel extends Model
  53. {
  54. private $attributes;
  55. private $attributeLabels;
  56. private $internalRelations;
  57. private $model;
  58. private $modelClassName;
  59. private $relationAttributes = [];
  60. private $rules;
  61. private $scenarios;
  62. /**
  63. * @var string 默认排序
  64. */
  65. public $defaultOrder;
  66. /**
  67. * @var string 分组
  68. */
  69. public $groupBy;
  70. /**
  71. * @var int 每页大小
  72. */
  73. public $pageSize = 10;
  74. /**
  75. * @var array 模糊查询
  76. */
  77. public $partialMatchAttributes = [];
  78. /**
  79. * @var array
  80. */
  81. public $relations = [];
  82. /**
  83. * SearchModel constructor.
  84. * @param $params
  85. * @throws NotFoundHttpException
  86. */
  87. public function __construct($params)
  88. {
  89. $this->scenario = 'search';
  90. parent::__construct($params);
  91. if ($this->model === null) {
  92. throw new NotFoundHttpException('Param "model" cannot be empty');
  93. }
  94. $this->rules = $this->model->rules();
  95. $this->scenarios = $this->model->scenarios();
  96. $this->attributeLabels = $this->model->attributeLabels();
  97. foreach ($this->safeAttributes() as $attribute) {
  98. $this->attributes[$attribute] = '';
  99. }
  100. }
  101. /**
  102. * @param ActiveQuery $query
  103. * @param string $attribute
  104. * @param bool $partialMath
  105. */
  106. private function addCondition($query, $attribute, $partialMath = false)
  107. {
  108. if (isset($this->relationAttributes[$attribute])) {
  109. $attributeName = $this->relationAttributes[$attribute];
  110. } else {
  111. $attributeName = call_user_func([$this->modelClassName, 'tableName']) . '.' . $attribute;
  112. }
  113. $value = $this->$attribute;
  114. if ($value === '') {
  115. return;
  116. }
  117. if ($partialMath) {
  118. $query->andWhere(['like', $attributeName, trim($value)]);
  119. } else {
  120. $query->andWhere($this->conditionTrans($attributeName, $value));
  121. }
  122. }
  123. /**
  124. * 可以查询大于小于和IN
  125. *
  126. * @param $attributeName
  127. * @param $value
  128. * @return array
  129. */
  130. private function conditionTrans($attributeName, $value)
  131. {
  132. switch (true) {
  133. case is_array($value):
  134. return [$attributeName => $value];
  135. break;
  136. case stripos($value, '>=') !== false:
  137. return ['>=', $attributeName, substr($value, 2)];
  138. break;
  139. case stripos($value, '<=') !== false:
  140. return ['<=', $attributeName, substr($value, 2)];
  141. break;
  142. case stripos($value, '<') !== false:
  143. return ['<', $attributeName, substr($value, 1)];
  144. break;
  145. case stripos($value, '>') !== false:
  146. return ['>', $attributeName, substr($value, 1)];
  147. break;
  148. case stripos($value, ',') !== false:
  149. return [$attributeName => explode(',', $value)];
  150. break;
  151. default:
  152. return [$attributeName => $value];
  153. break;
  154. }
  155. }
  156. /**
  157. * @return Model
  158. */
  159. public function getModel()
  160. {
  161. return $this->model;
  162. }
  163. /**
  164. * @param mixed $value
  165. */
  166. public function setModel($value)
  167. {
  168. if ($value instanceof Model) {
  169. $this->model = $value;
  170. $this->scenario = $this->model->scenario;
  171. $this->modelClassName = get_class($value);
  172. } else {
  173. $this->model = new $value;
  174. $this->modelClassName = $value;
  175. }
  176. }
  177. /**
  178. * @return array
  179. */
  180. public function rules()
  181. {
  182. return $this->rules;
  183. }
  184. /**
  185. * @return array
  186. */
  187. public function attributeLabels()
  188. {
  189. return $this->attributeLabels;
  190. }
  191. /**
  192. * @return array
  193. */
  194. public function scenarios()
  195. {
  196. return $this->scenarios;
  197. }
  198. /**
  199. * @param array $params
  200. * @return ActiveDataProvider
  201. */
  202. public function search($params)
  203. {
  204. $query = call_user_func([$this->modelClassName, 'find']);
  205. $dataProvider = new ActiveDataProvider(
  206. [
  207. 'query' => $query,
  208. 'pagination' => new Pagination(
  209. [
  210. 'forcePageParam' => false,
  211. 'pageSize' => $this->pageSize,
  212. ]
  213. ),
  214. ]
  215. );
  216. if (is_array($this->relations)) {
  217. foreach ($this->relations as $relation => $attributes) {
  218. $pieces = explode('.', $relation);
  219. $path = '';
  220. $parentPath = '';
  221. foreach ($pieces as $i => $piece) {
  222. if ($i == 0) {
  223. $path = $piece;
  224. } else {
  225. $parentPath = $path;
  226. $path .= '.' . $piece;
  227. }
  228. if (!isset($this->internalRelations[$path])) {
  229. if ($i == 0) {
  230. $relationClass = call_user_func([$this->model, 'get' . $piece]);
  231. } else {
  232. $className = $this->internalRelations[$parentPath]['className'];
  233. $relationClass = call_user_func([new $className, 'get' . $piece]);
  234. }
  235. $this->internalRelations[$path] = [
  236. 'className' => $relationClass->modelClass,
  237. 'tableName' => call_user_func([$relationClass->modelClass, 'tableName']),
  238. ];
  239. }
  240. }
  241. foreach ((array)$attributes as $attribute) {
  242. // $attributeName = str_replace('.', '_', $relation) . '_' . $attribute;
  243. $attributeName = $relation . '.' . $attribute;
  244. $tableAttribute = $this->internalRelations[$relation]['tableName'] . '.' . $attribute;
  245. $this->rules[] = [$attributeName, 'safe'];
  246. $this->scenarios[$this->scenario][] = $attributeName;
  247. $this->attributes[$attributeName] = '';
  248. $this->relationAttributes[$attributeName] = $tableAttribute;
  249. $dataProvider->sort->attributes[$attributeName] = [
  250. 'asc' => [$tableAttribute => SORT_ASC],
  251. 'desc' => [$tableAttribute => SORT_DESC],
  252. ];
  253. }
  254. }
  255. $query->joinWith(array_keys($this->relations));
  256. }
  257. if (is_array($this->defaultOrder)) {
  258. $dataProvider->sort->defaultOrder = $this->defaultOrder;
  259. }
  260. if (is_array($this->groupBy)) {
  261. $query->addGroupBy($this->groupBy);
  262. }
  263. $this->load($params);
  264. foreach ($this->attributes as $name => $value) {
  265. $this->addCondition($query, $name, in_array($name, $this->partialMatchAttributes));
  266. }
  267. return $dataProvider;
  268. }
  269. /**
  270. * @param string $name
  271. * @return mixed
  272. * @throws \yii\base\UnknownPropertyException
  273. */
  274. public function __get($name)
  275. {
  276. if (isset($this->attributes[$name])) {
  277. return $this->attributes[$name];
  278. }
  279. return parent::__get($name);
  280. }
  281. /**
  282. * @param string $name
  283. * @param mixed $value
  284. * @throws \yii\base\UnknownPropertyException
  285. */
  286. public function __set($name, $value)
  287. {
  288. if (isset($this->attributes[$name])) {
  289. $this->attributes[$name] = $value;
  290. } else {
  291. parent::__set($name, $value);
  292. }
  293. }
  294. }