[英]How to access all data from pivot table laravel?
I am a beginner in Laravel and am stuck with sending the data from pivot table to view. 我是Laravel的初学者,一直坚持将数据从数据透视表发送到视图。 I have two models one is "Supplier" and another is "Product" which I have created as follows:
我有两种模型,一种是“供应商”,另一种是我创建的“产品”,如下所示:
Supplier.php 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 Product.php
class Product extends Model
{
protected $keyType = 'string';
protected $primaryKey = 'product_id';
public $incrementing = false;
public function suppliers()
{
return $this->belongsToMany('App\Supplier');
}
}
Now I want to access all the data from the pivot table named as "inward_stock" from my controller and want to send it to the view named "inward-stock-list", I have created "inwardstockController" for that purpose and want to know how to send it to the view using that controller. 现在,我想从控制器访问名为“ inward_stock”的数据透视表中的所有数据,并将其发送到名为“ inward-stock-list”的视图,为此我创建了“ inwardstockController”,并且想知道如何使用该控制器将其发送到视图。
I think the most effective way is to create model for pivot table: 我认为最有效的方法是为数据透视表创建模型:
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: inwardstockController:
$inwardStocks = InwartStock::with(['product', 'supplier'])->get();
View: 视图:
@foreach($inwardStocks as $inwardStock)
{{ $inwardStock->supplier->id }}
{{ $inwardStock->product->id }}
@endforeach
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.