I have 4 MySQL tables, using PHP and Laravel 7
- members
- deductions
- payments
- payment_deductions
Now I want to display every single member in a row with his/her single payment and all other deductions. (Assuming One person has only one payment)
The DB schema is as follows
and here is the HTML table I want to display
Here is the query I'm using but it duplicates the data.
        $payments = Payment::leftJoin('members', 'payments.member_id', '=', 'members.id')
        ->leftJoin('payment_deductions', 'payments.id', '=', 'payment_deductions.payment_id')
        ->leftJoin('deductions', 'payment_deductions.deduction_id', '=', 'deductions.id')
        ->select(
            'members.*',
            'payment_deductions.*',
        )
        ->orderBy("member_id", "ASC")
        ->get()->toArray();
The resulting array repeats every member as per their deductions.
Is there any way to get this data better? Something like a nested array of deductions with each member?
Here are the models
Member
    namespace App;
    use Illuminate\Database\Eloquent\Model;
    use Carbon\Carbon;
    class Member extends Model
    {
        protected $fillable = [
            'full_name',
            'email',
            'created_by',
        ];
    }
Payment
    namespace App;
    use Illuminate\Database\Eloquent\Model;
    class Payment extends Model
    {
        protected $fillable = [
            'member_id',
            'total_amount',
            'payable_amount',
            'created_by',
        ];
        public function deductions() {
           return $this->belongsToMany(Deduction::class,'payment_deductions')->withTimestamps();
        }
    }
Deduction
    namespace App;
    use Illuminate\Database\Eloquent\Model;
    class Deduction extends Model
    {
        protected $fillable = [
        'title',
        'priority',
        'created_by',
        ];
    }


 
    