私は現在3つのデータベーステーブルを持っていると思いますので、このようなモデル: Laravel:これらの異質な関係を定義し、それらをすべて1つのビューに渡す方法は?
証券Yにおける製品Xの
- 証券
- 製品
- 額は今のところ私は「3つのモデルを持っています「StockProducts」および「StockProductsAmount」を含む。 StockProductsAmountには、StockProductsおよびStockProductsAMountのIDに2つの外部キーがあります。
どのように関係を定義する必要がありますか? App \ StockProductsAmountでは、私はすでにこれを定義した:
class StockProductsAmount extends Model { public function stock() { return $this->hasOne('App\Stock'); } public function stockproduct() { return $this->hasOne('App\StockProducts'); } }
は私もどこか他の
hasMany
-Relationshipを定義する必要はないのですか?しかしここで?また、3つのテーブルの値に1つのビューでアクセスするにはどうすればよいですか。
これは私が今持っているものです。コメントアウトされた値は、私がEloquent関係を定義した後に始めたものです。
public function stockOverview() { $products = StockProducts::all(); $stocks = Stock::all(); $amounts = StockProductsAmount::all(); //$stock = StockProductsAmount::all()->with('stock')->with('stockproducts'); $data = array( 'stocks' => $stocks, 'products' => $products, 'amount' => $amounts ); return view('stock.overview')->with($data); }
ありがとうございます。
編集:テーブルの構造:
株式:
Schema::create('stocks', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('color1'); $table->string('color2'); $table->timestamps(); });
Stock_Products:
Schema::create('stock_products', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->timestamps(); });
証券商品金額:あなたのテーブルstructurに基づいて
Schema::create('stock_products_amounts', function (Blueprint $table) { $table->increments('id'); $table->integer('fk_stock')->unsigned(); $table->foreign('fk_stock')->references('id')->on('stocks'); $table->integer('fk_stockproduct')->unsigned(); $table->foreign('fk_stockproduct')->references('id')->on('stock_products'); $table->integer('amount'); $table->timestamps(); });
ストックXに複数の商品Xが存在することはできますか? – TheFallen
関係の理解を深めるためにテーブルの構造を共有することができます。 –
@ TheFallenすべての在庫はX製品を持つことができ、すべての製品は金額テーブルに入れることができます。したがって、すべての製品はすべての在庫に含めることができます。 – Scarwolf