Search code examples
laravelmany-to-manyrelationshiplaravel-6

Laravel ManyToMany relations where to save item total?


Need advice what is best practice for Many To Many relations where to save item total column? For ex. I have Users and Inventory Table, they are connected by pivot table and in pivot table i also have column total of attached Inventory. Is it correct way or can someone advice me which will be best way for it?

DB Structure


Solution

  • I may suggest :

    1) Make the pair of foreign keys unique (user_id, inventory_id) to prevent duplicates

    2) Make a seperate model for you pivot table : App\InventoryUser

    3) Make use of updateOrCreate Laravel Elequent function

    According to Elequent Docs

    updateOrCreate will update an existing model or create a new model if none exists

    E.g

    $oldTotal = InventoryUser::where(['user_id' => 'x', 'inventory_id' => 'y'])->select('total') ?? 0;
    $inventoryUser = InventoryUser::updateOrCreate(
        ['user_id' => 'x', 'inventory_id' => 'y'],
        ['total' => $oldTotal+1]
    );
    

    Or even better

    $inventoryUser = InventoryUser::updateOrCreate(
            ['user_id' => 'x', 'inventory_id' => 'y']
    )->increment('total'); // You must Set DEFAULT value to (0) for total column in your database