简体   繁体   English

Laravel按数据透视表列排序

[英]Laravel sort by pivot table column

I am trying to sort an eloquent query in laravel by a column from the pivot table. 我正在尝试通过数据透视表中的列对laravel中的雄辩查询进行排序。

Basically as long as the product is favorited by the user, it is added to the pivot table, and it should first show the favorited ones, and then the remaining ones. 基本上,只要用户喜欢该产品,就将其添加到数据透视表中,并且应该首先显示该产品,然后显示其余产品。 Since I will be using foreach in the blade. 因为我将在刀片中使用foreach。

products table contains these columns: 产品表包含以下列:

id, category, product_name, priority, status, created_at, updated_at

users table contains these columns: users表包含以下列:

id, name, email, created_at, updated_at

with the following in the users model: 在用户模型中具有以下内容:

public function favorites()
{
    return $this->belongsToMany(Products::class, 'favorites', 'user_id', 'product_id')
                ->withTimeStamps();
}

favorites table contains these columns: 收藏夹表包含以下列:

id, user_id, product_id, created_at, updated_at

In the controller, the eloquent query is currently: 在控制器中,雄辩的查询当前为:

$productinprogress = Products::all()
    ->sortByDesc("priority")
    ->where('status', 'inprogress');

I am just confused as to how to tackle this. 我只是对如何解决这个问题感到困惑。

Your help is appreciated. 感谢您的帮助。 Thank you so much. 非常感谢。

you can use something like bellow: 您可以使用以下波纹管:

$productinprogress = Products::all()
   ->where('status', 'inprogress')
   ->sortByDesc("priority");

and if you want an efficient solution using eager loading and loading favorites too, use following code 如果您还想使用急于加载和加载收藏夹的高效解决方案,请使用以下代码

 $productinprogress = Products::all()
    ->with('favorites')
    ->where('status', 'inprogress')
    ->sortByDesc("priority");

I think you should make two queries to avoid loading duplicate products, first one for favorite products, second one should be some thing like this: 我认为您应该进行两个查询以避免加载重复的产品,第一个查询最喜欢的产品,第二个查询应该是这样的:

Products::all()->sortByDesc("priority")->where('status', 'inprogress')->whereNotIn('id', $favorite_products);

and then in the blade file, you make two foreach, first one for favorites, and 2end for others. 然后在刀片文件中,创建两个foreach,第一个用于收藏夹,第二个用于其他。

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

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