vendredi 29 septembre 2017

Laravel return collection with relation and with calculation

I have a laravel application which has a model Client.

A client has many addresses, many jobs and many transactions.

I've the following relations on my client model:

public function jobs()
    {
        return $this->hasMany('App\Job','client_id');
    }

public function addresses()
    {
        return $this->hasMany('App\Address','client_id');
    }

public function Fees()
    {
        return $this->hasMany('App\Transaction','client_id');
    }

I then have another function on that model which calculates the value

public function balance() 
    {
        return $this->Fees()->where('status',2)->sum('gross');
    }

I'm trying to return a list of all clients along with their addresses, jobs and the balance of each client.

I've tried the following:

 $customers = $user->clients()->with('balance')->with('jobs')->with('addresses')->get();

I get the following error

Call to a member function addEagerConstraints() on string

This will no doubt be the eagerloading and the fact the balance() isn't a collection but I'm wondering how I would achieve the same result without having to loop through to build an array.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2woxRrt
via IFTTT

Aucun commentaire:

Enregistrer un commentaire