Home > Back-end >  Accessing a secondary relationship from primary model without intermediate table with foreign keys
Accessing a secondary relationship from primary model without intermediate table with foreign keys

Time:01-28

I have this structure:

model: OrderItem
belongsTo ProductInfo

model: ProductInfo
hasMany OrderItem
hasMany Barcode

model: Barcode
belongsTo ProductInfo

How can I make an easy accessible relationship in the OrderItem to get the Barcodes that match the same product_info_id? The product_infos table is of course not a classic intermediate table containing the foreign keys.

I know this is probably a very simple question since the relationship is also very basic, but I'm kind of confused with all the answers I find online and in the Laravel docs for slightly different situations. F.e. hasManyThrough is not working out in any way here.

CodePudding user response:

This relationship is correct you can access barcode like

$order->ProductInfo->barcodes 

This will return an array of barcodes

CodePudding user response:

Instead of using the pivot model, try this.

OrderItem belongs to many Barcode

Then the Barcode model,

table: barcodes Barcode belongs to many OrderItem

And last create a pivot table php artisan make:migration create_barcodes_order_items_table and make two columns for foreign_ids, order_item_id and barcode_id.

It would automatically take care of your relationship unless you didn't do anything outside the pattern.

Then you can get all barcodes of order and all orders for a barcode. $order->barcodes

  •  Tags:  
  • Related