【问题标题】:Laravel Call to undefined method Illuminate\Database\Query\Builder::post_images()Laravel 调用未定义的方法 Illuminate\Database\Query\Builder::post_images()
【发布时间】:2017-05-26 16:53:26
【问题描述】:

我正在 Laravel 5.2 中尝试这个查询

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

之后我收到了这个错误Call to undefined method Illuminate\Database\Query\Builder::post_images()

我不明白这里有什么错误。

这里users tableposts Table 有关系,Posts 表与post_images table 有关系

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

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

请指导我该如何解决这个问题。

【问题讨论】:

  • 您只能在相关型号上制作User::with() / User::withCount()。而且您没有与 post_images 表相关的用户。但是你可以做这样的事情:stackoverflow.com/a/39681353/4771277
  • 请贴出你的模特关系码
  • @Autista_z 我已经创建了这个关系
  • @Jono20201 关系代码更新
  • 不应该withCount('post_images')withCount('postimages') 吗?

标签: laravel laravel-5 laravel-5.2


【解决方案1】:

正如@linktoahref 所说,withCount 将关系方法名称作为参数,而不是表或列名。

withCount('postimages')应该解决你的问题

【讨论】:

    猜你喜欢
    • 2018-10-03
    • 2016-10-22
    • 1970-01-01
    • 2014-04-23
    • 2014-04-25
    • 2017-02-20
    • 2017-10-04
    • 2018-05-17
    • 2015-12-17
    相关资源
    最近更新 更多