Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

tieupham304's avatar

How to calculate total sales with different reference types

I have these tables:

Stories
- id
Chapter
- id
- story_id
Payments
- id
- type
- reference_id
- reference_type
- amount

Example datas:

  • Stories Table
| id 	    | name         	            | status    	        |
|----	|--------------	|-----------	|
| 1  	    | Eragon 1              	| published      |
| 2  	    | Harry Potter 			| published 	   |
  • Chapteres Table:
| id 	    | name      	    | story_id 	    | status    	        |
|----	|-----------	|----------	|-----------	|
| 1  	    | Chapter 1 	    | 1        	            | published 	    |
| 2     	| Chapter 1 	    | 2                     	| published 	    |
| 3  	   | Chapter 2    	| 1        	            | published   	|
  • Payments Table
| id 	| type  	| reference_id 	| reference_type     	| amount 	| created_at          	|
|----	|-------	|--------------	|--------------------	|--------	|---------------------	|
| 1  	| COMBO 	| 1            	| App/Models/Story   	| 10000  	| 2023-05-22 23:12:47 	|
| 2  	| BUY   	| 2            	| App/Models/Chapter 	| 100    	| 2023-05-22 23:14:47 	|
| 3  	| BUY   	| 3            	| App/Models/Chapter 	| 100    	| 2023-05-22 23:16:47 	|

I calculate the total sales of the Story with :

$now = Carbon::now();
$weekStartDate = ->startOfWeek()->format('Y-m-d H:i');
$weekEndDate = $now->endOfWeek()->format('Y-m-d H:i');

Story::join('payments', 'stories.id', '=', 'payments.reference_id')
            ->groupBy('stories.id')
            ->whereNotNull('payments.amount')
            ->whereIn('payments.transaction', ['DONATE', 'COMBO', 'BUY'])
            ->where(function ($query) {
                $query->where(function ($subquery) {
                    $subquery->where('payments.reference_type', '=', Story::class);
                })->orWhere(function ($subquery) {
                    $subquery->whereIn(
                        'payments.reference_id',
                        Chapter::select('id')->where('story_id', 'stories.id')
                    )->where('payments.reference_type', '=', Chapter::class);
                });
            })
        ->where('payments.created_at', '>=', $weekStartDate)
        ->where('payments.created_at', '<=', $weekEndDate)
        ->select(
        'stories.id', 'stories.name', 'stories.image','stories.introduce',
            DB::raw('sum(payments.amount) as total')
        )
        ->orderBy('total', 'desc')->get();

But for stories with Buy transaction with reference_type = Chapter::class, it is not counted. Can anyone help me with the exact calculation?

0 likes
0 replies

Please or to participate in this conversation.