I have a basic three tables users and guests and posts
Also i have table named user_views: to store unique users views of posts
post_id user_id 1 10002 2 10003 3 10011 And another table named guest_views: to store unique guests views of posts
post_id guest_id 1 10002 2 10003 3 10011 In Post model i have:
public function user_views() { return $this->hasMany('App\Models\PostUserView'); } public function guest_views() { return $this->hasMany('App\Models\PostGuestView'); } In the following code get the correct results but with two different keys.
$posts = Post::all() ->withCount('user_views') ->withCount('guest_views') I thought of merge user_views and guest_views then compute count as follow but the result only includes count of user_views
public function views() { return $this->user_views()->unionAll($this->guest_views()); } After you perform the following code
$posts = Post::all() ->withCount('views') ->withCount('user_views') ->withCount('guest_views') I get this result
"views_count": 5, "user_views_count": 5, "guest_views_count": 2, The expected result for prevues example is:
"views_count": 7, "user_views_count": 5, "guest_views_count": 2, Also i try to use sql query as follow
public function views() { return DB::raw("(select * from post_views) union all (select * from post_guest_views)"); } But get
"Call to undefined method Illuminate\Database\Query\Expression::getRelationExistenceCountQuery()" So I'd like to get total number of views from all users and guest for each post.
select posts.*, (select count(*) fromuser_views` whereposts.id=user_views.post_id) + (select count(*) fromguest_viewswhereposts.id=guest_views.post_id) , .... `