skip to Main Content

I want to get relation:

Package::whereIn('id', $cart_items)->with('course')->select('id', 'name')->get();

It return successfully as object, but now I need to count this relation, I did:

function courses(){
 return $this->hasMany('AppModelsCourse', 'package_id','id');
}
    
public function getCourseCount()
{
 return $this->courses()->count();
}

And then:

Package::whereIn('id', $cart_items)->with('getCourseCount')->select('id', 'name')->get();

But give me this error:

Call to a member function addEagerConstraints() on int

Any idea?


I also used withCount but it return empty array.

Package::whereIn('id', $cart_items)->withCount('courses')->select('id', 'name')->get();

2

Answers


  1. withCount() accepts a relation name as a parameter, so try this

    Package::whereIn('id', $cart_items)->withCount('courses')->get();
    

    without the select()

    Login or Signup to reply.
  2. From the docs:

    If you’re combining withCount with a select statement, ensure that you call withCount after the select method

    So try the following code:

    Package::whereIn('id', $cart_items)->select('id', 'name')->withCount('courses')->get();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search