Hi everyone!
I am building an application, where users can control their rental properties / leases. For each lease, a user can attach a connection to their bank account (to automatically import recent transactions).
A lease can have many bank accounts attached.
//Lease.php
/**
* A lease can have many bank accounts attached
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function bankAccounts(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(BankAccount::class);
}
Further, a bank account can have many transactions attached to it.
//BankAccount.php
/**
* A bank account can have many bank transactions.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function transactions()
{
return $this->hasMany(BankTransaction::class);
}
For a lease, a user can change the associated bank account. In this scenario, I don't want to delete the transactions already imported (as these can be used elsewhere in the application), but just add the new bank account to the applicaton, and mark it as the "active" one.
How can I best do this, while also always ensuring that, I only have one active bank account per lease?
I was thinking of adding this method to the Lease model, and adding an is_active column to the database schema:
/**
* A lease can only have one active bank account.
*
*/
public function bankAccount()
{
return $this->bankAccounts()->firstWhere('is_active', TRUE);
}
However, I am not sure how I can enforce/control that a lease can only have one active bank account?