我是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”,并且想知道如何使用该控制器将其发送到视图。
答案 0 :(得分:2)
我认为最有效的方法是为数据透视表创建模型:
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