BaseModel.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * Author: 芸众商城 www.yunzshop.com
  5. * Date: 24/02/2017
  6. * Time: 16:36
  7. */
  8. namespace app\common\models;
  9. use app\backend\modules\goods\observers\SettingObserver;
  10. use app\common\exceptions\AppException;
  11. use app\common\exceptions\ShopException;
  12. use app\common\traits\ReplaceableModelTrait;
  13. use app\common\traits\ValidatorTrait;
  14. use app\framework\Database\Eloquent\Builder;
  15. use Carbon\Carbon;
  16. use Illuminate\Database\Eloquent\Model;
  17. use app\framework\Database\Eloquent\Collection;
  18. use Illuminate\Foundation\Validation\ValidatesRequests;
  19. use Illuminate\Support\Facades\DB;
  20. /**
  21. * Class BaseModel
  22. * @package app\common\models
  23. * @property int id
  24. * @property int created_at
  25. * @property int updated_at
  26. * @property int deleted_at
  27. * @method static self uniacid()
  28. * @method static self pluginId()
  29. * @method static Collection get()
  30. * @method static self find(string $id)
  31. * @method static self first()
  32. * @method static self select(...$fields)
  33. * @method static self where(...$where)
  34. * @method static self whereNot(...$where)
  35. * @method static self orWhere(...$where)
  36. * @method static self whereBetween(array $where)
  37. * @method static self with($with)
  38. * @method static self whereIn($attribute, ...$where)
  39. * @method static self whereNotIn(...$where)
  40. * @method static self whereHas(...$where)
  41. * @method static Collection pluck($field)
  42. * @method static int count()
  43. * @method static float sum()
  44. * @method static self join(...$join)
  45. * @method static self insert()
  46. * @method static self set()
  47. * @method static self exclude($fields)
  48. * @method static self orderBy(...$field)
  49. * @method static self whereRaw(...$field)
  50. * @method static self getModel()
  51. * @method static string value($fields)
  52. * @method static self groupBy(...$field)
  53. * @method static self delete()
  54. */
  55. class BaseModel extends Model
  56. {
  57. use ValidatorTrait;
  58. use ValidatesRequests;
  59. use ReplaceableModelTrait;
  60. protected $search_fields;
  61. static protected $needLog = false;
  62. public function getTableName()
  63. {
  64. return app('db')->getTablePrefix() . $this->getTable();
  65. }
  66. /**
  67. * 模糊查找
  68. * @param $query
  69. * @param $params
  70. * @return mixed
  71. */
  72. public function scopeSearchLike(Builder $query, $params)
  73. {
  74. $search_fields = $this->search_fields;
  75. $query->where(function (Builder $query) use ($params, $search_fields) {
  76. foreach ($search_fields as $search_field) {
  77. $query->orWhere($search_field, 'like', '%' . $params . '%');
  78. }
  79. });
  80. return $query;
  81. }
  82. /**
  83. * 默认使用时间戳戳功能
  84. *
  85. * @var bool
  86. */
  87. public $timestamps = true;
  88. /**
  89. * 获取当前时间
  90. *
  91. * @return int
  92. */
  93. public function freshTimestamp()
  94. {
  95. return time();
  96. }
  97. /**
  98. * 避免转换时间戳为时间字符串
  99. *
  100. * @param \DateTime|int $value
  101. * @return \DateTime|int
  102. */
  103. public function fromDateTime($value)
  104. {
  105. return $value;
  106. }
  107. /**
  108. * select的时候避免转换时间为Carbon
  109. *
  110. * @param mixed $value
  111. * @return mixed
  112. */
  113. // protected function asDateTime($value) {
  114. // return $value;
  115. // }
  116. /**
  117. * 从数据库获取的为获取时间戳格式
  118. */
  119. //public function getDateFormat() {
  120. // return 'U';
  121. // }
  122. /**
  123. * 后台全局筛选统一账号scope
  124. * @param Builder $query
  125. * @return $this|Builder
  126. */
  127. public function scopeUniacid(Builder $query)
  128. {
  129. if (\YunShop::app()->uniacid === null || \YunShop::app()->uniacid === '') {
  130. return $query;
  131. }
  132. return $query->where($this->getTable() . '.uniacid', \YunShop::app()->uniacid);
  133. }
  134. /**
  135. * 递归获取$class 相对路径的 $findClass
  136. * @param $class
  137. * @param $findClass
  138. * @return null|string
  139. */
  140. public static function recursiveFindClass($class, $findClass)
  141. {
  142. $result = substr($class, 0, strrpos($class, "\\")) . '\\' . $findClass;
  143. if (class_exists($result)) {
  144. return $result;
  145. }
  146. if (class_exists(get_parent_class($class))) {
  147. return self::recursiveFindClass(get_parent_class($class), $findClass);
  148. }
  149. return null;
  150. }
  151. /**
  152. * 获取与子类 继承关系最近的 $model类
  153. * @param $model
  154. * @return null|string
  155. * @throws ShopException
  156. */
  157. public function getNearestModel($model)
  158. {
  159. $result = self::recursiveFindClass(static::class, $model);
  160. if (isset($result)) {
  161. return $result;
  162. }
  163. throw new ShopException('获取关联模型失败');
  164. }
  165. /**
  166. * 用来区分订单属于哪个.当插件需要查询自己的订单时,复写此方法
  167. * @param $query
  168. * @param int $pluginId
  169. * @return mixed
  170. */
  171. public function scopePluginId(Builder $query, $pluginId = 0)
  172. {
  173. return $query->where('plugin_id', $pluginId);
  174. }
  175. /**
  176. * 用来区分订单属于哪个.当插件需要查询自己的订单时,复写此方法
  177. * @param $query
  178. * @param null $uid
  179. * @return mixed
  180. */
  181. public function scopeUid(Builder $query, $uid = null)
  182. {
  183. if (!isset($uid)) {
  184. $uid = \YunShop::app()->getMemberId();
  185. }
  186. $function = is_array($uid) ? 'whereIn' : 'where';
  187. return $query->$function($this->getTable() . '.uid', $uid);
  188. }
  189. public function scopeMine(Builder $query)
  190. {
  191. return $query->where('uid', \YunShop::app()->getMemberId());
  192. }
  193. protected static function boot()
  194. {
  195. parent::boot(); // TODO: Change the autogenerated stub
  196. if (static::$needLog) {
  197. static::observe(new SettingObserver);
  198. }
  199. }
  200. private function getCommonModelClass($class)
  201. {
  202. if (get_parent_class($class) == self::class) {
  203. return $class;
  204. }
  205. return $this->getCommonModelClass(get_parent_class($class));
  206. }
  207. /**
  208. * Get the class name for polymorphic relations.
  209. *
  210. * @return string
  211. */
  212. public function getMorphClass()
  213. {
  214. return $this->getCommonModelClass(parent::getMorphClass());
  215. }
  216. public function pushAppends($appends)
  217. {
  218. $this->appends = array_merge($this->appends, $appends);
  219. return $this;
  220. }
  221. /**
  222. * @return mixed
  223. * @throws \Exception
  224. */
  225. public function columns()
  226. {
  227. $cacheKey = 'model_' . $this->getTable() . '_columns';
  228. if (!\Cache::has($cacheKey)) {
  229. $columns = \Illuminate\Support\Facades\Schema::getColumnListing($this->getTable());
  230. cache([$cacheKey => $columns], Carbon::now()->addSeconds(3600));
  231. return $columns;
  232. }
  233. return cache($cacheKey);
  234. }
  235. /**
  236. * @param $column
  237. * @return bool
  238. * @throws \Exception
  239. */
  240. public function hasColumn($column)
  241. {
  242. return in_array($column, $this->columns());
  243. }
  244. /**
  245. * @param $query
  246. * @param array $excludeFields
  247. * @return mixed
  248. * @throws \Exception
  249. */
  250. public function scopeExclude($query, $excludeFields)
  251. {
  252. if (!is_array($excludeFields)) {
  253. $excludeFields = explode(',', $excludeFields);
  254. }
  255. $fields = array_diff($this->columns(), $excludeFields) ?: [];
  256. return $query->select($fields);
  257. }
  258. public function getRelationValue($key)
  259. {
  260. // If the key already exists in the relationships array, it just means the
  261. // relationship has already been loaded, so we'll just return it out of
  262. // here because there is no need to query within the relations twice.
  263. if ($this->relationLoaded($key)) {
  264. return $this->relations[$key];
  265. }
  266. // If the "attribute" exists as a method on the model, we will just assume
  267. // it is a relationship and will load and return results from the query
  268. // and hydrate the relationship's value on the "relationships" array.
  269. if (method_exists($this, $key)) {
  270. return $this->getRelationshipFromMethod($key);
  271. }
  272. return $this->getRelationshipFromExpansions($key, static::class);
  273. }
  274. /**
  275. * 从模型扩展中获取关联模型
  276. * @param $method
  277. * @param $class
  278. * @return mixed
  279. */
  280. public function expansionMethod($method, $class)
  281. {
  282. if (!isset(static::$expansions)) {
  283. static::$expansions = \app\common\modules\shop\ShopConfig::current()->get('shop-foundation.model-expansions') ?: [];
  284. }
  285. if (!empty(static::$expansions)) {
  286. foreach ($this->getExpansions($class) as $expansion) {
  287. if (method_exists($expansion, $method)) {
  288. return (new $expansion)->$method($this);
  289. }
  290. }
  291. }
  292. // 递归到此类为止避免死循环
  293. if (get_parent_class($class) !== self::class) {
  294. return $this->expansionMethod($method, get_parent_class($class));
  295. }
  296. }
  297. /**
  298. * 从模型扩展中载入
  299. * @param $key
  300. * @param $class
  301. * @return mixed
  302. */
  303. private function getRelationshipFromExpansions($key, $class)
  304. {
  305. if (isset(static::$expansions)) {
  306. foreach ($this->getExpansions($class) as $expansion) {
  307. if (method_exists($expansion, $key)) {
  308. return (new $expansion)->getRelationshipFromExpansion($key, $this);
  309. }
  310. }
  311. }
  312. // 递归到此类为止避免死循环
  313. if (get_parent_class($class) !== self::class) {
  314. return $this->getRelationshipFromExpansions($key, get_parent_class($class));
  315. }
  316. }
  317. /**
  318. * 模型扩展
  319. * @var Collection
  320. */
  321. protected static $expansions;
  322. /**
  323. * 设置扩展
  324. * @param $expansions
  325. */
  326. public static function setExpansions($expansions)
  327. {
  328. static::$expansions = $expansions;
  329. }
  330. /**
  331. * 获取扩展设置
  332. * @return mixed
  333. */
  334. private function getExpansions($class)
  335. {
  336. return static::$expansions[$class];
  337. }
  338. /**
  339. * @param \Illuminate\Database\Query\Builder $query
  340. * @return Builder|\Illuminate\Database\Eloquent\Builder|static
  341. */
  342. public function newEloquentBuilder($query)
  343. {
  344. return new Builder($query);
  345. }
  346. public function beforeSaving()
  347. {
  348. return true;
  349. }
  350. public function afterSaving()
  351. {
  352. return true;
  353. }
  354. /**
  355. * 递归格式化金额字段
  356. * @param $attributes
  357. * @return array
  358. */
  359. protected function formatAmountAttributes($attributes)
  360. {
  361. // 格式化价格字段,将key中带有price,amount的属性,转为保留2位小数的字符串
  362. $attributes = array_combine(array_keys($attributes), array_map(function ($value, $key) {
  363. if (is_array($value)) {
  364. $value = $this->formatAmountAttributes($value);
  365. } else {
  366. if (str_contains($key, 'price') || str_contains($key, 'amount')) {
  367. $value = sprintf('%.2f', $value);
  368. }
  369. }
  370. return $value;
  371. }, $attributes, array_keys($attributes)));
  372. return $attributes;
  373. }
  374. /**
  375. * 校验参数
  376. * @param $request
  377. * @param array $rules
  378. * @param array $messages
  379. * @param array $customAttributes
  380. * @throws AppException
  381. */
  382. public function validate($request, array $rules, array $messages = [], array $customAttributes = [])
  383. {
  384. $validator = $this->getValidationFactory()->make($request, $rules, $messages, $customAttributes);
  385. //$validator->errors();
  386. if ($validator->fails()) {
  387. throw new AppException($validator->errors()->first());
  388. }
  389. }
  390. public function getPlugin()
  391. {
  392. if (isset($this->plugin_id) && $this->plugin_id > 0) {
  393. return app('plugins')->findPlugin($this->plugin_id);
  394. }
  395. return null;
  396. }
  397. public function batchUpdate(array $update, $whenField = 'id', $whereField = 'id', $raw = false)
  398. {
  399. $when = [];
  400. $ids = [];
  401. foreach ($update as $sets) {
  402. # 跳过没有更新主键的数据
  403. if (!isset($sets[$whenField])) {
  404. continue;
  405. }
  406. $whenValue = $sets[$whenField];
  407. foreach ($sets as $fieldName => $value) {
  408. #主键不需要被更新
  409. if ($fieldName == $whenField) {
  410. array_push($ids, $value);
  411. continue;
  412. };
  413. if ($raw) {
  414. $when[$fieldName][] = "when {$whenValue} then {$value}";
  415. } else {
  416. $when[$fieldName][] = "when '{$whenValue}' then '{$value}'";
  417. }
  418. }
  419. }
  420. # 没有更新的条件id
  421. if (!$when) {
  422. return false;
  423. }
  424. $query = $this->whereIn($whereField, $ids);
  425. # 组织sql
  426. foreach ($when as $fieldName => &$item) {
  427. $item = DB::raw("case $whenField " . implode(' ', $item) . ' end ');
  428. }
  429. return $query->update($when);
  430. }
  431. }