1
votes

I am trying this Query in Laravel 5.2

User::with(['posts'])
  ->withCount('post_images')
  ->orderBy('post_images_count', 'desc')
  ->take(8)
  ->get();

After that I got this error Call to undefined method Illuminate\Database\Query\Builder::post_images()

I did not understand what mistake is here.

Here users table has relation with posts Table and Posts table has relation with post_images table

public function posts()
{
    return $this->hasMany(Post::class);
}

public function postimages()
{
    return $this->hasManyThrough(PostImage::class, Post::class);
}

Please guide How can I fix this.

1
You can make User::with() / User::withCount() only on related Models. And you dont have related User with post_images table. But you can make somthing like this: stackoverflow.com/a/39681353/4771277 - Autista_z
Please post your model's relationship code - Jono20201
@Autista_z I have already created this relation ship - Harry
@Jono20201 relationship code is updated - Harry
Shouldn't withCount('post_images') be withCount('postimages') ? - linktoahref

1 Answers

2
votes

As @linktoahref said, withCount is taking a relation method names as argument, not a table nor a column name.

withCount('postimages')should fix your problem