SuggestTransformer.php 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Administrator
  5. * Date: 2019/6/15
  6. * Time: 11:07
  7. */
  8. namespace App\Transformers\Post;
  9. use App\Models\Post;
  10. use App\Models\PostCollect;
  11. use App\Models\PostComment;
  12. use App\Models\PostDislike;
  13. use App\Models\PostLike;
  14. use Carbon\Carbon;
  15. use League\Fractal\TransformerAbstract;
  16. class SuggestTransformer extends TransformerAbstract
  17. {
  18. public function __construct($uid)
  19. {
  20. $this->uid = $uid;
  21. }
  22. public function transform(Post $post)
  23. {
  24. $imgs = [];
  25. foreach($post->imgs as $img){
  26. $imgs[] = $img['img'];
  27. }
  28. $comment = [];
  29. $comments = PostComment::where('post_id', $post['id'])->where('parent_id', 0)->orderBy('id', 'desc')->limit(2)->get();
  30. foreach($comments as $item){
  31. $replyCount = $item->reply->count();
  32. $replies = PostComment::where('parent_id', $item->id)->orderBy('id', 'desc')->limit(2)->get();
  33. $reply = [];
  34. foreach($replies as $val){
  35. $reply[] = [
  36. 'nickname' => $val->nickname,
  37. 'reply_username' => $val->reply_username,
  38. 'content' => $val->content,
  39. ];
  40. }
  41. $comment[] = [
  42. 'id' => $item->id,
  43. 'nickname' => $item->nickname,
  44. 'content' => $item->content,
  45. 'reply_count' => $replyCount,
  46. 'reply' => $reply,
  47. ];
  48. }
  49. $topic = [];
  50. foreach($post->topic() as $key => $val){
  51. $topic[] = [
  52. 'id' => $key,
  53. 'name' => $val
  54. ];
  55. }
  56. return [
  57. 'show_type' => 0,
  58. 'id' => $post['id'],
  59. 'type' => $post['type'],
  60. 'created_at' => Carbon::parse($post['created_at'])->diffForHumans(),
  61. 'uid' => $post['uid'],
  62. 'username' => $post['username'],
  63. 'avatar' => $post['avatar'],
  64. 'topic' => $topic,
  65. 'title' => $post['title'],
  66. 'content' => $post['content'],
  67. 'location' => $post['location'],
  68. 'img' => $post['img'],
  69. 'imgs' => $imgs,
  70. 'video' => $post['video'],
  71. 'pv' => $post->data->pv,
  72. 'praise_count' => $post->data->praise_count,
  73. 'comment_count' => $post->data->comment_count,
  74. 'will_collect_bean' => $post->data->will_collect_bean,
  75. 'is_like' => PostLike::where('post_id', $post['id'])->where('uid', $this->uid)->exists()?1:0,
  76. 'is_dislike' => PostDislike::where('post_id', $post['id'])->where('uid', $this->uid)->exists()?1:0,
  77. 'is_collect' => PostCollect::where('post_id', $post['id'])->where('uid', $this->uid)->exists()?1:0,
  78. 'comment' => $comment,
  79. 'is_follow' => 1,
  80. ];
  81. }
  82. }