Home > database >  laravel count relation return Call to a member function addEagerConstraints() on int
laravel count relation return Call to a member function addEagerConstraints() on int

Time:10-30

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('App\Models\Course', '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();

CodePudding user response:

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();

CodePudding user response:

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

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

without the select()

  • Related