Laravel 5.2 orderBy 与 Count 的关系导致 SQL 错误,因为尝试获取列而不是计数失败

Laravel 5.2 orderBy relation withCount results in SQL error because of failed attempt to get column instead of count

目标是在我的过滤中根据浏览量对我的广告系列进行排序,这就是为什么我有一个与我的广告系列相关的分析table

我的活动模型(数据库名称是 "ads"):

public function views() {
    return $this->hasMany('App\Analytic', 'foreign_id', 'id')->where('foreign_type', '=', 'campaign');
}

我的过滤控制器:

$query = Ad::withCount('views')->with('tags');
$query->where("is_active", "=", 1);
$query->where("status", "=", 1);
$query->orderBy('views_count', 'DESC');
$campaigns = $query->get();

现在不写没有 $query-> 部分的原因是因为查询有很多 if 语句,具体取决于过滤设置。

我得到的错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'views_count' in 'order clause' (SQL: select count(*) as aggregate from `ads` where `is_active` = 1 and `status` = 1 and `from_year` >= 7 and `to_year` <= 88 and `price` >= 1000 and `price` <= 64000 order by `views_count` desc) 

错误是它试图获取列,但我不明白为什么。 如果我尝试在我的 blade 模板中访问 $campaign->views_count,它显示计数就好了。

谢谢你抽出时间,我希望有人能告诉我我做错了什么。

您遇到的错误是 count() 方法而非 get() 的结果。 像这样

$query = Ad::withCount('views')->with('tags');
$query->where("is_active", "=", 1);
$query->where("status", "=", 1);
$query->orderBy('views_count', 'DESC');
$campaignCount = $query->count();

wich 将复杂的 select 部分替换为:

select count(*) as aggregate

如果您需要 count() 和 get(),请这样做:

$query = Ad::withCount('views')->with('tags');
$query->where("is_active", "=", 1);
$query->where("status", "=", 1);
$campaignCount = $query->count();

$query->orderBy('views_count', 'DESC');
$campaigns = $query->get();