2016-07-25 8 views
0

私はLaravelとは初めて作業しています。私はの商品の商品の長さ、幅、高さなどの詳細をすべて含んだテーブルを持っています。の親品目部分と多くの子供完全な製品。親部品と子部品の両方が全く同じ特性(すなわち、長さ、幅、高さなど)を有しており、すべての子部品は要件に応じて個々の製品として取り扱うことができる。また、完成した製品を得るために、すべての親部品に必要な子部品の数も記録する必要があります。Laravelのテーブル内の多対多の関係5.2

例:1親部品+ 2子部品#1子部品#2完成品。

具体的には、1マスターカートン+ 2パッド+ 3パーティション= 1ボックス。

私はモデル製品と移行製品このようなを作成しました:

php artisan make:model Product -m 

の移行は、次のようになります。

Schema::create('products', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->string('product_code'); 
     $table->integer('part_type_id'); 
     $table->integer('box_type_id'); 
     $table->float('length'); 
     $table->float('breadth'); 
     $table->float('height'); 
     $table->float('ply'); 
     $table->float('gsm_a_base'); 
     $table->float('gsm_a_flute'); 
     $table->float('gsm_b_base'); 
     $table->float('gsm_b_flute'); 
     $table->float('gsm_top'); 
     $table->timestamps(); 
    }); 

今、私が保持するテーブルを作成する必要があります詳細は

| parent_product_id | child_product_id | qty_of_child_per_parent |

parent_product_idchild_product_id製品テーブルでIDフィールドの外部キーです。この関係を達成するのを手伝ってください。それが良い方法があれば教えてください。ありがとう

答えて

0

あなたが述べ列を持つ新しいテーブルを作成したい場合は、あなたがあなたのモデルに関係関数を追加することができるはずです(のは、この表のparent_child_productsに名前を付けましょう):withPivotを追加することにより

public function childProducts() { 
    return $this->belongsToMany(Product::class, 'parent_child_products', 'child_product_id', 'parent_product_id')->withPivot('qty_of_child_per_parent'); 
} 
public function parentProducts() { 
    return $this->belongsToMany(Product::class, 'parent_child_products', 'child_product_id', 'parent_product_id')->withPivot('qty_of_child_per_parent'); 
} 

()の部分には、関連項目のピボットオブジェクトに数量の列が追加されます。これは次のようにアクセスできます。

$sumOfChildren = 0; 
foreach($product->childProducts as $childProduct) { 
    $sumOfChildren += $childProduct->pivot->qty_of_child_per_parent; 
}