skip to Main Content

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


  1. I would define an Accessor on your Friend model:

    class Friend extends Model {
      protected function engagements(): Attribute {
        return Attribute::make(
          get: fn () => $this->activities_count ?? 0 + $this->reactions_count ?? 0
        );
      }
    }
    

    Then, as long as you include withCount(['activities', 'reactions']) in your Query, you’ll be able to do something like this:

    Controller Code:

    $friends = Friend::withCount(['activities', 'reactions'])
    ->where('user_id', auth()->id())
    ->get();
    
    return view('example')->with(['friends' => $friends]);
    

    In your View:

    @foreach ($friends as $friend)
      {{ $friend->engagements }}
    @endforeach
    

    https://laravel.com/docs/10.x/eloquent-mutators#defining-an-accessor

    Login or Signup to reply.
  2. This old way but work for me.

    class Friend extends Model {
      public function reactions(){
        return $this->hasMany(FriendsReaction::class);
      }
    
      public function activities(){
        return $this->hasMany(FriendsActivity::class);
      }
    
      public function getCount(){
          return count($this->reactions() + $this->activities());
      }
    }
    

    and use it

    $friends = Friend::where('user_id', auth()->id())->first();
    $friends->getCount();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search