0 レビュー
1 回答
php-ピボットテーブルlaravelからすべてのデータにアクセスする方法は?
私はLaravelの初心者であり、ピボットテーブルからビューにデータを送信することに固執しています。私は2つのモデルを持っています。1つは「サプライヤー」で、もう1つは「製品」で、次のように作成しました。
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
レビュー
答え :
解決策:
最も効果的な方法は、ピボットテーブルのモデルを作成することだと思います:
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');
}
}
internalstockController:
$inwardStocks = InwartStock::with(['product', 'supplier'])->get();
表示:
@foreach($inwardStocks as $inwardStock)
{{ $inwardStock->supplier->id }}
{{ $inwardStock->product->id }}
@endforeach
わからない
同様の質問
私たちのウェブサイトで同様の質問で答えを見つけてください。