Laravel 5.5:如何获得特定商店的畅销商品?

时间:2018-05-26 19:31:16

标签: laravel-5 eloquent laravel-5.5

我的表格如下:

商店 [id]

库存 [id, shop_id]

订单 [id, shop_id]

order_item [order_id, inventory_id, quantity]

型号:

//Shop
class Shop extends Model
{
    public function inventories()
    {
        return $this->hasMany(Inventory::class);
    }

    public function orders()
    {
        return $this->hasMany(Order::class);
    }
}

//Inventory
class Inventory extends Model
{
    public function shop()
    {
        return $this->belongsTo(Shop::class);
    }

    public function orders()
    {
        return $this->belongsToMany(Order::class, 'order_items')
                    ->withPivot('quantity');
    }
}

//Order
class Order extends Model
{
    public function shop()
    {
        return $this->belongsTo(Shop::class);
    }

    public function inventories()
    {
        return $this->belongsToMany(Inventory::class, 'order_items')
                    ->withPivot('quantity');
    }
}

现在我想要一个特定商店的5个畅销库存,最好的方法是什么?

我在使用Laravel 5.5

3 个答案:

答案 0 :(得分:1)

select s.id,sum(oi.quantity) as total from munna.shops as s
join munna.inventories as iv on s.id=iv.shop_id
join munna.orders as o on iv.shop_id=o.shop_id
join munna.order_items as oi on o.id=oi.order_id
group by s.id
order by total desc limit 5

答案 1 :(得分:1)

首先,通过查看 order_item 上的表格, ,order_id和inventory_id 肯定会来到同一家商店吗?我想是的,因为如果没有,你会有2个不同的商店,顶级订单相同。我不知道你为什么这样做,但它有点令人困惑,不能弄明白为什么,但我会尝试这个:

public function topOrders()
{
    $items = DB::table('shops')
                  ->join('orders', 'shops.id', '=', 'orders.shop_id')
                  ->join('inventories', 'shops.id', '=', 'inventories.shop_id')
                  ->join('order_items', 'orders.id', '=', 'order_items.order_id')
                  ->orderBy('quantity', 'desc')
                  ->take(5)
                  ->get();
    return $items;
}

我写的内容应该从所有3行中选择所有内容,如果你只想选择你想要选择的项目或任何你可以指定它添加一个select子句

答案 2 :(得分:1)

虽然这是我自己的问题,但我自己找到了解决方案,并希望与社区分享解决方案。我想用Eloquent解决它,因为我需要视图上的模型,并且不想再次查询模型。

    Inventory::where('shop_id', \Auth::user()->shop_id)
                    ->select(
                        'inventories.*',
                        \DB::raw('SUM(order_items.quantity) as quantity')
                    )
                    ->join('order_items', 'inventories.id', 'order_items.inventory_id')
                    ->groupBy('inventory_id')
                    ->get();

我希望这会帮助有类似问题的人。感谢