簡體   English   中英

如何從數據透視表Laravel訪問所有數據?

[英]How to access all data from pivot table laravel?

我是Laravel的初學者,一直堅持將數據從數據透視表發送到視圖。 我有兩種模型,一種是“供應商”,另一種是我創建的“產品”,如下所示:

Supplier.php

class Supplier extends Model
{
    protected $keyType = 'string';

    public $incrementing = false;

    public function products()
    {
        return $this->belongsToMany(
                'App\Product',
                'inward_stock',
                'supplier_id',
                'product_id'
            )->withPivot(
                'product_dimension',
                'quantity',
                'expiry_date',
                'type',
                'QR_code',
                'sales_price',
                'arrival_date',
                'occassion',
                'discount_percentage',
                'payment_date',
                'cost',
                'paid_status',
                'sku'
            )->withTimestamps();
    }
}

Product.php

class Product extends Model
{
    protected $keyType = 'string';
    protected $primaryKey = 'product_id';

    public $incrementing = false;

    public function suppliers()
    {
        return $this->belongsToMany('App\Supplier');
    }
}

現在,我想從控制器訪問名為“ inward_stock”的數據透視表中的所有數據,並將其發送到名為“ inward-stock-list”的視圖,為此我創建了“ inwardstockController”,並且想知道如何使用該控制器將其發送到視圖。

我認為最有效的方法是為數據透視表創建模型:

class InwardStock extends Model
{
    protected $table = 'inward_stock';

    public function supplier()
    {
        return $this->belongsTo('App\Supplier', 'supplier_id', 'supplier_id');
    }

    public function product()
    {
        return $this->belongsTo('App\Product', 'product_id', 'product_id');
    }
}

inwardstockController:

$inwardStocks = InwartStock::with(['product', 'supplier'])->get();

視圖:

@foreach($inwardStocks as $inwardStock)
    {{ $inwardStock->supplier->id }}
    {{ $inwardStock->product->id }}
@endforeach

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM