I’ve next database structure:
friends:
id,
first_name,
last_name,
friends_activities:
friend_id,
user_id,
type (enum),
created_at,
friends_reactions:
friend_id,
user_id,
type (enum),
And I need to count all friends_reactions and friends_activity together as e.g. engagements_count.
So far I’ve created eloquent relationship in the Friend.php model:
public function reactions()
{
return $this->hasMany(FriendsReaction::class);
}
public function activities()
{
return $this->hasMany(FriendsActivity::class);
}
And for now, I’m getting them with:
$friends = Friend::query()->withCount('activities', 'reactions')->where('user_id', auth()->id());
Do you know how to pull the activities and reactions together as engagements
(activities + reactions) via eloquent withCount (eager loaded of course)?
2
Answers
I would define an Accessor on your
Friend
model:Then, as long as you include
withCount(['activities', 'reactions'])
in your Query, you’ll be able to do something like this:Controller Code:
In your View:
https://laravel.com/docs/10.x/eloquent-mutators#defining-an-accessor
This old way but work for me.
and use it