total (using sum())
I've got three tables:
users
-id
-name
-...
addresses
-id
-user_id
-...
transactions
-id
-address_id
-amount
Now I would like the whole sum of all transactions for a certain user.
What's the best way to archive this using eloquent?
dd($forwarded_total->sum('addresses.transactions.amount'));
returns 0 all the time.
You must have following relationships in your models
a users hasMany addresses
an addrese belongsTo a user
an addresse hasMany transactions
a transaction belongsTo a addrese
and then for a user you can call
$user->adresses()->transactions()->sum('amount');
@StefanVoinea
These are my relationships from my models:
user model:
public function addresses()
{
return $this->hasMany('App\Address');
}
address model:
public function user()
{
return $this->belongsTo('App\User');
}
public function transactions()
{
return $this->hasMany('App\Transaction');
}
transaction model:
public function address()
{
return $this->belongsTo('App\Address');
}
Now when I try to use this in my view it says:
Call to undefined method Illuminate\Database\Query\Builder::adresses()
in my view I use:
{{ Auth::user()->adresses()->transactions()->sum('amount') }}
you named addresses and call adresses with one d
I'd suggest using Eloquent's hasManyThroughrelationship, since a User has many Transactions through the Address model.
// App/User.php
public transactions() {
return $this->hasManyThrough(App\Transaction::class, App\Address::class);
}
Then, you can just do it like
Auth::user()->transactions()->sum('amount');
Much cleaner solution, since you don't have to be explicit about the Address model.
Please or to participate in this conversation.