Home » Php » php – How can I get the sum of a column in an eloquent relationship where two tables don't have a direct join

php – How can I get the sum of a column in an eloquent relationship where two tables don't have a direct join

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m building a larval app that pulls data from a live database used on another website. I can’t modify the database in any way. What I’m looking to achieve is to get a sum total of the amount in the payments table for a client.
I have the following database structure.

Clients

id

Customers

id

ClientCustomer

client_id
customer_id

Subscriptions

id
client_id
customer_id

Subscription_Billings

id 
subscription_id
payment_id
created

Payments

id
customer_id
amount
created

These are the models

Client.php

public function customers()
{
    return $this->belongsToMany('App\Customer');
}

public function subscriptions()
{
    return $this->hasMany('App\Subscription');
}

public function subscriptionBillings()
{
    return $this->hasManyThrough(
        'App\SubscriptionBilling',
        'App\Subscription'
    );
}

Customer.php

public function clients()
{
    return $this->belongsToMany('App\Client');
}

public function payments()
{
    return $this->hasMany('App\Payment');
}

Subscription.php

public function client()
{
    return $this->belongsTo('App\Client');
}

public function SubscriptionBillings()
{
    return $this->hasMany('App\SubscriptionBilling');
}

SubscriptionBilling.php

public function subscription()
{
    return $this->belongsTo('App\Subscription');
}

public function payment()
{
    return $this->hasOne('App\Payment');
}

Payment.php

public function subscriptionBilling()
{
    return $this->belongsTo('App\SubscriptionBilling');
}

public function customer()
{
    return $this->belongsTo('App\Customer');
}

Then in my controller I have tried the below.

Controller.php

$client = Client::find(1);
$amount = $client->subscriptionBillings()
        ->whereRaw("DATE_FORMAT(subscription_billings.createddate, '%Y-%m-%d') >= '{$startDate}'")
        ->whereRaw("DATE_FORMAT(subscription_billings.createddate, '%Y-%m-%d') <= '{$endDate}'")
        ->whereHas('payment', function (Builder $query) {
            $query->sum('amount');
        });

When I try the above I get the following error

Column not found: 1054 Unknown column ‘subscription_billings.payment_id’ in ‘where clause’ (SQL: select sum(amount) as aggregate from payments where subscription_billings.payment_id = payment.id

In the larval debugger I’m getting a message “The SELECT statement has no WHERE clause and could examine many more rows than intended”

Again what I’m trying to get is the sum of amount in payments for a given client. I don’t know if I need or how to create a relationship between the client and payments.

How to&Answers: