1

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.

5
  • 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 Commented May 26, 2017 at 8:21
  • Please post your model's relationship code Commented May 26, 2017 at 8:24
  • @Autista_z I have already created this relation ship Commented May 26, 2017 at 8:30
  • @Jono20201 relationship code is updated Commented May 26, 2017 at 8:30
  • Shouldn't withCount('post_images') be withCount('postimages') ? Commented May 26, 2017 at 8:43

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.