从 laravel 中的中间 table 获取数据

get data from intermediate table in laravel

我有 2 个模型(销售发票和产品)具有多对多关系

在 SaleInvoice 模型中:

public function products()
    {
        return $this->belongsToMany(Product::class, 'sale_invoice_product', 'saleInvoice_id', 'product_id')->withPivot('count');
    }

在产品型号中:

    public function saleInvoices()
    {
        return $this->belongsToMany(SaleInvoice::class, 'sale_invoice_product', 'product_id', 'saleInvoice_id');
    }

这是sale_invoice_product table(中级table)

中记录的数据示例
id | saleInvoiceId | product_id | count
1  |      1500     |      1     | 3
2  |      1500     |      3     | 2
3  |      1500     |      4     | 4
4  |      1501     |      1     | 1
5  |      1501     |      4     | 1

我如何从这个 table 访问产品和销售发票的数据,如下所示(在 api 请求的 json 模式下)

product_id | product_name | count | saleInvoice | date
     1             LG         3        1500        2020-05-12
     3             SONY       2        1500        2020-05-13
     4             OT         4        1500        2020-05-17
     1             LG         1        1501        2020-05-19
     4             OT         1        1501        2020-05-22

我想在 SaleInvoiceController 中 return 一个 json 格式的文件

你的工作很好,只需为此模型创建一个 API 资源并根据需要发送属性,要访问数据透视表 table,你可以使用 $product->pivot->count

您可以尝试其中一种方法

  • 建立 sale_invoice_product table 与 SaleInvoiceProduct 的关系模型。然后在你的控制器中手动构建JSON
  • 为它构建一个 SQL 视图和模型

解决方案 1:构建模型到中间 table 并手动构建 JSON

假设您构建了一个名为 SaleInvoiceProduct 的模型,该模型与 Products table 具有 product() 关系,与 SaleInvoices 具有 saleInvoice() 关系] table。在你的控制器中你可以这样做

$resultInvoiceProducts = [];
$allSaleInvoiceProducts = SaleInvoiceProduct::all();
foreach ($allSaleInvoiceProducts as oneSaleInvoiceProduct) {
     $tempSaleInvoiceProduct = new stdClass();
     $tempSaleInvoiceProduct->product_id = oneSaleInvoiceProduct->product_id;
     $tempSaleInvoiceProduct->product_name = oneSaleInvoiceProduct->product->name;
     $tempSaleInvoiceProduct->saleInvoiceId = oneSaleInvoiceProduct->saleInvoiceId;
     $tempSaleInvoiceProduct->data = oneSaleInvoiceProduct->saleInvoice->date;
     array_push($resultInvoiceProducts, $tempSaleInvoiceProduct);
}

解决方案 2:使用 SQL 视图

您可以创建一个 SQL 视图,该视图使用联接来构造您需要的数据

   DROP VIEW IF EXISTS vSaleInvoiceProduct;
   CREATE VIEW vSaleInvoiceProduct AS
   SELECT sp.product_id,
          sp.saleInvoiceId,
          sp.`count`,
          p.product_name,
          s.`date`
   FROM SaleInvoiceProduct sp
   LEFT JOIN SaleInvoices s on sp.saleInvoiceId = s.saleInvoiceId
   LEFT JOIN Products p on sp.product_id = p.product_id

然后你可以为这个视图创建一个 Laravel 模型,就像你为任何 table 做的一样,调用它的 ::all() 方法并直接 return结果 json()