Cisaia
1 month ago

hasManyThrough relationship with data from intermediate table

Posted 1 month ago by Cisaia

Hello! I am having a problem a with hasManyThrough relationship. I got it to work relatively easily, but now I would like the final product, the collection of items assigned to a product, to include the id and order fields of my intermediate table.

I have three tables

  • products

    • id
  • product_item_rel

    • id
    • product_id
    • item_id
    • order
  • product_items

    • id
    • a bunch of other information

I have created a hasManyThrough relationship on my products model

public function items()
{
    return $this->hasManyThrough(
        'App\Models\ProductItemModels\product_items',               // name of the final model
        'App\Models\ProductItemModels\product_item_rel',            // name of the intermediate model
        'product_id',                                                  // foreign key on the intermediate mode
        'id',                                                       // foreign key on the final model
        'id',                                                       // local key
        'item_id'                                                // local key of the intermediate model
    );
}

This all works great, and using $product->items, I can get all assigned items to my product

The problem I am running into, is that I want two fields from my intermediate table (id, order) to be included in the final collection. Is there a way to rewrite the hasManyThrough relationship to include these two fields from the INTERMEDIATE table?

The reason I need this is

  1. I would like to be able to delete the connection between product and product_item by referencing the connecting product_item_rel id
  2. I would like to be able to order the items based off the "order" field on the product_item_rel

Please sign in or create an account to participate in this conversation.