查询:带有可自定义变量的产品数量,例如颜色,尺寸

时间:2019-10-27 05:55:04

标签: php laravel laravel-5

我想从 stock_reports 表中生成报告,在这里我要显示每种产品的数量,例如颜色,基于created_at的尺寸意味着每个批次。我已经使用了以下查询,但是我需要一些改进。

$stockReport = DB::table('products')
        ->rightjoin('stock_reports','stock_reports.product_id','products.id')
         ->join('sizes','sizes.id','stock_reports.size_id')
         ->join('colors','colors.id','stock_reports.color_id')
        ->select('products.product_name','stock_reports.created_at'
            DB::raw('sum(quantity)'))

        ->groupby('stock_reports.created_at','products.product_name')
        ->orderby('stock_reports.created_at','desc')
        ->get();

输出应为:

Name           Quantity    CREATED_AT
product_name1  XL-BLUE-15, L-RED-20 2019-08-12 
product_name2  L-BLUE-15, S-RED-20 2019-08-12
product_name1  M-BLUE-15, L-RED-20 2019-08-13

我的表格结构:

产品:

 id product_name

库存报告

 id
 product_id
 size_id
 quantity
 color_id
 sold_price

尺寸

  id
  size_name

颜色

  id
  color_name

1 个答案:

答案 0 :(得分:1)

首先,通过终端或手动创建模型

php artisan make:model stock_reports
php artisan make:model sizes
php artisan make:model products
php artisan make:model colors

在字典应用程序中添加到文件stock_reports.php

    public function product()
    {
        return $this->belongsTo(products::class, 'product_id');
    }
    public function size()
    {
        return $this->belongsTo(sizes::class, 'size_id');
    }
    public function color()
    {
        return $this->belongsTo(colors::class, 'color_id');
    }

将功能报告添加到products.php

    public function reports()
    {
        return $this->hasMany(stock_reports::class, 'product_id');
    }

最后在您的控件中使用:


        $stock_reports=stock_reports::
        with('product')
        ->get()->sortBy('product.product_name')->sortBy('created_at');

        foreach($stock_reports as $report)
        {
            $product_name=$report->product->product_name;
            $size_name=$report->size->size_name;
            $color_name=$report->color->color_name;
            $qty_products=$report->product->reports()->count();

            // use wherever you need to use it

        }

结果:


Name Quantity CREATED_AT
T-shirt C x-Red-1 2019-09-11 18:55:12
Name Quantity CREATED_AT
T-shirt D xl-Blue-1 2019-09-11 18:55:12
Name Quantity CREATED_AT
T-shirt A xl-Blue-1 2019-09-12 18:55:12
Name Quantity CREATED_AT
T-shirt B x-White-1 2019-09-13 18:55:12

一些建议:

  1. 使用pagination laravel代替-> get()

  2. 使用外键