【问题标题】:how to use orderBy after countBy?在countBy之后如何使用orderBy?
【发布时间】:2021-07-31 10:09:27
【问题描述】:

我有两个表productsvotes,每个product 可以有多个投票。

我需要的是orderBy DESC 的每个产品的总票数。

这是我的代码:

public function render()
{
    $pria = Product::find($this->product->id);
    $result = $pria->votes()
        ->get('voted')
        ->countBy('voted');

    foreach ($result as $value) {
        echo $value;
    }

    return view('livewire.Raishomar');
}

我有总票数,但是如何排序呢?

【问题讨论】:

  • 您需要按总票数对产品进行排序,对吧?

标签: mysql laravel laravel-livewire


【解决方案1】:

您可以在集合上使用sortBy() - 但在 SQL/Eloquent 中执行此操作要好得多。 Laravel 在查询构建器上提供了一个 withCount() 方法供您使用。

$products = Product::withCount('votes')
                   ->orderBy('votes_count', 'desc')
                   ->get();

您的$results 收藏现在有一个附加属性:votes_count。在应用->get()之前,您可以添加where()的任何条件,您需要过滤您的查询。

【讨论】:

    猜你喜欢
    • 2017-02-16
    • 2018-09-16
    • 2021-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多