Process data from pivot table relationships

Posted 1 year ago by lmartins

Hi,

I'm looking to build an app where a organization can make multiple purchases of a given product, with every purchase adding a X amount of credits for that product to that organization.

So, the Schema looks like this:

        Schema::create('organizations', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });

        Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });

        Schema::create('purchases', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('credits')->unsigned();
            $table->integer('product_id')->unsigned();
            $table->foreign('product_id')
                    ->references('id')
                    ->on('products');
            $table->integer('organization_id')->unsigned();
            $table->foreign('organization_id')
                    ->references('id')
                    ->on('organizations');
            $table->timestamps();
        });

Then on the Organization controller I load the product model for each purchase:

    public function show(Organization $organization) {
        $organization->load('purchases.product');
        return view('organizations.show', compact('organization'));
    }

Which then allows me to display a list of purchases like this:

##PURCHASES

  • 2 months ago | Prod A | 51 Credits
  • 4 months ago | Prod A | 62 Credits
  • 6 months ago | Prod B | 118 Credits
  • 8 months ago | Prod A | 346 Credits
  • 9 months ago | Prod C | 377 Credits

These credits will control actions the organization can do, so my goal now is first to get the total credits for each product, so I can easily display and interact with those total amounts.

How would you approach this?

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