[英]Many-To-Many Relationship within a table in Laravel 5.2
我是第一次與Laravel合作。 我有一個方案,其中有一個產品表,其中包含產品(瓦楞紙箱)的所有詳細信息,例如長度,寬度,高度等。很少有產品具有父部件和許多子部件,這些部件構成了完整的產品。 父部件和子部件都具有完全相同的屬性(即長度,寬度,高度等),並且每個子部件都可以並且必須根據要求被視為單個產品。 而且,我還必須記錄每個父部件要獲得成品所需的子部件數。
例如:1個父部件+ 2個子部件_1 + 1個子部件_2 = 1個制成品。
更具體地說: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_id和child_product_id是產品表中id字段的外鍵。 請幫助我建立這種關系,或者讓我知道是否有更好的方法。 謝謝
如果要使用您聲明的列創建一個新表(將該表命名為parent_child_products),則應該能夠向模型添加關系函數:
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');
}
通過添加withPivot()部分,數量列將添加到相關項目的樞軸對象上,您可以像這樣訪問:
$sumOfChildren = 0;
foreach($product->childProducts as $childProduct) {
$sumOfChildren += $childProduct->pivot->qty_of_child_per_parent;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.