【问题标题】:Laravel OrderBy Relationship count with paginationLaravel OrderBy 与分页的关系计数
【发布时间】:2015-11-21 14:58:26
【问题描述】:

我有很多项目,每个都有很多订单,有些完成了,有些没有。

我想按已完成订单的数量订购它们,如下所示:

$products = $products->orderBy(function($product) {
    return $product->orders->where('status', 2)->count();
})->paginate(15);

我知道订单调用不是这样工作的,但这是最好的展示问题的方法。 SortBy 不起作用,因为我想使用分页。

【问题讨论】:

  • 你的 laravel 是什么版本的?
  • 不要在你的函数中返回,因为这会停止你的查询。
  • 我知道这段代码是错误的。您不能传递 orderBya 函数,因为它必须将其转换为数据库查询。但它解释了我遇到的问题。
  • 所以您想根据等于 2 的状态计数对您的产品进行排序,对吗?
  • @aldrin27 没错。

标签: php laravel pagination query-builder


【解决方案1】:

如果可行,试试这个:

    $categories = Prodcuts::with(array('orders' => function($query) {
       $query->select(DB::raw('SELECT * count(status) WHERE status = 2 as count'))
        $query->orderBy('MAX(count)')
     }))->paginate(15);

    return View::make('products.index', compact('categories'));

注意:这未经测试。

【讨论】:

  • ` 语法错误或访问冲突:1064 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以获取在 'SELECT * count(status) WHERE status = 2 as count from orders where orders.p' at line 1 (SQL: select SELECT * count(status) WHERE status = 2 as count from orders` where orders.@ 附近使用的正确语法987654326@ in (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15) order by MAX(count)asc)`
【解决方案2】:

终于找到了解决问题的好办法:

$products = $products->join('orders', function ($join) {
                        $join->on('orders.product_id', '=', 'products.id')
                            ->where('orders.status', '=', 2);
                    })
                    ->groupBy('products.id')
                    ->orderBy('count', $order)
                    ->select((['products.*', DB::raw('COUNT(orders.product_id) as count')]))->paginate(50);

【讨论】:

【解决方案3】:

从 5.2 开始,您可以使用withCount 来计算关系结果。

在这种情况下

$products = $products->withCount(['orders' => function ($query) {
    $query->where('status', 2);
}]);

参考:https://laravel.com/docs/5.2/eloquent-relationships

【讨论】:

    猜你喜欢
    • 2022-01-16
    • 2017-03-25
    • 2021-07-01
    • 2014-08-04
    • 2019-05-14
    • 1970-01-01
    • 2013-08-11
    • 1970-01-01
    • 2020-07-08
    相关资源
    最近更新 更多