繁体   English   中英

雄辩地获得所有用户,但先从相关表订购

[英]Eloquent get ALL users, but order from related table first

我正在建立我的第一个Laravel项目,并试图吸引所有用户并按他们拥有的产品数量对其进行排序。 这是我的代码:

我有User.php

public function products()
{
    return $this->hasMany(Product::class, 'user_id');
}

Product.php

public function user()
{
    return $this->belongsTo(User::class, 'user_id', 'id');
}

UsersController.php

    public function index()
    {

        $user = User::select(DB::raw('users.*, count(*) as `products`'))
            ->join('products', 'users.id', '=', 'products.user_id')
            ->groupBy('user_id')
            ->orderBy('products', 'desc')
            ->get();

        return response($user, 200);

    }

这将返回以下JSON:

{
    id: 5,
    role: 1,
    state: 1,
    name: "Frida Greenfelder",
    email: "cummings.alfreda@example.org",
    email_verified_at: "2019-09-11 13:23:20",
    date_of_birth: "1981-01-28",
    created_at: "2019-09-11 13:23:20",
    updated_at: "2019-09-11 13:23:20",
    products: 8
},

这是可行的,但是,这只会返回拥有产品的用户并对其进行排序。 我想做的是吸引所有用户,然后首先按他们拥有的产品数量对其进行排序。 有些用户没有产品,这意味着他们的用户ID不在产品表中。 对于没有产品的用户,它应该只向用户返回产品:0。

我将如何去做呢? 我在网上搜索该确切的问题/解决方案时遇到了一些麻烦,因此也遇到了这个问题。

您可以使用Eloquent:

public function index()
{ 

    $user = User::with('products')->withCount('products')->orderBy('products_count', 'desc')->get();

   return response($user, 200);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM