DistSlugTrait.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. namespace App\Traits;
  3. use ArrayAccess;
  4. use Illuminate\Database\Eloquent\Builder;
  5. use Illuminate\Database\Eloquent\SoftDeletingScope;
  6. use Illuminate\Support\Facades\Event;
  7. use InvalidArgumentException;
  8. use Spatie\EloquentSortable\EloquentModelSortedEvent;
  9. use Spatie\EloquentSortable\Sortable;
  10. /*
  11. * slug
  12. */
  13. trait DistSlugTrait
  14. {
  15. /*
  16. * 生成slug
  17. */
  18. public static function generateSlug($slug,$id=0) {
  19. //截取50个字符
  20. $slug = truncateString($slug, 50);
  21. $self = new self();
  22. $model = $self->model();
  23. $slug = generateSlug($slug);
  24. for ($i=0;$i<3;$i++) {
  25. if ($id > 0) {
  26. $count = $model->where('id','!=',$id)->where('slug', $slug)->where('dist_id', getDistributorId())->count();
  27. } else {
  28. $count = $model->where('slug', $slug)->where('dist_id', getDistributorId())->count();
  29. }
  30. if ($count == 0) {
  31. return $slug;
  32. } else {
  33. $slug = $slug . '-' . generateRandomString(2);
  34. }
  35. }
  36. return $slug . '-' . generateRandomString(5);
  37. }
  38. public static function isRepeatedSlug($id,$slug) {
  39. $id = intval($id);
  40. $self = new self();
  41. $model = $self->model();
  42. $count = $model->where('id','!=',$id)->where('slug', $slug)->where('dist_id', getDistributorId())->count();
  43. if ($count > 0) {
  44. return true;
  45. } else {
  46. return false;
  47. }
  48. }
  49. }