You can create an intermediate HasManyThrough relationship between User and Journey by using Confirmation by following these steps:
- Define the relationship on the User model.
- Define the relationship on the Journey model.
- Define the relationship on the Confirmation model.
Here is an example of how to define the relationships on the User and Journey models:
Define the relationships on the User and Journey models
class User extends Model
{
protected $hasMany = [
'journeys' => [Journey::class],
];
}
class Journey extends Model
{
protected $hasMany = [
'confirmations' => [Confirmation::class],
];
}
Define the relationship on the Confirmation model
class Confirmation extends Model
{
protected $belongsTo = [
'user' => [User::class],
'journey' => [Journey::class],
];
}
Get the sum for a column of the journeys table by going through the confirmations table
$user = User::find(1);
$totalAmount = $user->journeys()
->whereHas('confirmations')
->sum('total_amount');
This code will first get all of the journeys that the user has confirmed. It will then use the sum() method to get the sum of the total_amount column for all of the journeys.
The output of this code will be the total amount for all of the journeys that the user has confirmed.