1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
| class User extends Model { public function posts() { return $this->hasMany(Post::class); } public function comments() { return $this->hasMany(Comment::class); } public function profile() { return $this->hasOne(UserProfile::class); } public function roles() { return $this->belongsToMany(Role::class); } }
class Post extends Model { public function user() { return $this->belongsTo(User::class); } public function category() { return $this->belongsTo(Category::class); } public function tags() { return $this->belongsToMany(Tag::class); } public function comments() { return $this->hasMany(Comment::class); } public function approvedComments() { return $this->hasMany(Comment::class) ->where('status', 'approved'); } }
class PostService {
public function getPopularPostsWithDetails() { return Post::with([ 'user:id,name,avatar', 'category:id,name,slug', 'tags:id,name', 'approvedComments' => function ($query) { $query->with('user:id,name') ->latest() ->limit(3); } ]) ->withCount(['comments', 'approvedComments']) ->where('status', 'published') ->where('view_count', '>=', 100) ->orderBy('view_count', 'desc') ->paginate(10); }
public function getUserPostStats($userId) { return User::with([ 'posts' => function ($query) { $query->select('id', 'user_id', 'status', 'view_count', 'created_at'); } ]) ->withCount([ 'posts', 'posts as published_posts_count' => function ($query) { $query->where('status', 'published'); }, 'posts as draft_posts_count' => function ($query) { $query->where('status', 'draft'); } ]) ->withSum('posts', 'view_count') ->find($userId); } }
|