'Accessing a secondary relationship from primary model without intermediate table with foreign keys

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.



Solution 1:[1]

This relationship is correct you can access barcode like

$order->ProductInfo->barcodes 

This will return an array of barcodes

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jainam shah
Solution 2 Suresh Hemal