php - Many-To-Many Relationship within a table in Laravel 5.2 -
i'm working laravel first time. have scenario have products table contains details of product (corrugated box) length, breadth, height etc. few products have parent part , many child parts constitute become complete product. both parent , child parts have same properties (i.e. length, breadth, height etc) , every child part can , has treated individual product per requirement. and, have record how many child parts necessary every parent part finished product.
ex: 1 parent part + 2 child parts_1 + 1 child parts_2 = 1 finished product.
to more specific: 1 master carton + 2 pads + 3 partitions = 1 box.
i have created model product , migration products this:
php artisan make:model product -m
migration looks this:
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(); });
now have create table holds details like
| parent_product_id | child_product_id | qty_of_child_per_parent |
where parent_product_id , child_product_id foreign keys of id field in products table. please me achieve relationship or let me know if there's better way of doing it. thank you
if you'd create new table columns stated (let's name table parent_child_products), should able add relation functions model:
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'); }
by adding withpivot() part, quantity column added on pivot object of related item, can access this:
$sumofchildren = 0; foreach($product->childproducts $childproduct) { $sumofchildren += $childproduct->pivot->qty_of_child_per_parent; }
Comments
Post a Comment