【问题标题】:Laravel eloquent order by custom attributeLaravel eloquent order by custom 属性
【发布时间】:2022-01-11 09:40:59
【问题描述】:

我有一个total_views 属性添加到我的Product 模型中,就像这样

public function getTotalViewsAttribute(){

  return (int)$this->views()->sum('count');

}

views()Product 上的关系,就像这样

public function views()
{
        return $this->morphMany(View::class, 'viewable');
}

我想做的是通过total_views 订购我的Product。或者换句话说,按views() 关系的总和排序。

我已尝试在查询中使用->orderBy('total_views'),但它似乎没有按预期工作。

我们将不胜感激。

【问题讨论】:

标签: laravel eloquent


【解决方案1】:

Eloquent getter 只能工作,当查询被执行时,你当前的代码不能工作。我总是在查询中使用withCount()

$products = Product ::withCount(['views'])->get();

计数将在名为 views_count; 的属性上。

foreach ($products as $product) {
    $product->views_count; // get view count
}

也可以按列排序,因为它会出现在查询返回的 SQL 中。

Product ::withCount(['views'])->orderBy('views_count', 'desc')->get();

【讨论】:

    猜你喜欢
    • 2021-03-02
    • 2018-03-29
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 2023-02-26
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多