1

Let us say there are four tables "User" "Location", "Currency", "Account. My question is If you have an 'account' called savings that has a 'location' in a place that uses a different 'currency', but this account is universal so many user can have this account, but all those users can have the account in different currency zones.

How can I write this out in Eloquent?

My thought process in solving this:

  1. Have a currency foreign key that links to a location table.
  2. The location table will then link to the users table with a foreign key
  3. Afterward any account that that user has would be displayed with the locations currency.

Any idea how I could also work it if the user has multiple accounts, but each account could have a different currency?

Thank you in advance.

My eloquent:

    $voucher = account::Where('Location','=', Auth::User()-> Location)->where('Currency','=','Dollar')->get();
aowusuda
  • 11
  • 2
  • What have you tried so far? Please check [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) – steven7mwesigwa Oct 07 '22 at 05:13

1 Answers1

0

User Model:

// relationship to account
public function account() {
   return $this->hasMany(Account::class);
}

Account Model:

// relationship to user
public function user() {
   return $this->belongsTo(Account::class); 
}

// relationship to location
public function location() {
    return $this->belongsTo(Location::class);
}

Location Model:

// relationship to account
public function account() {
   return $this->hasMany(Account::class);
}

// relationship to currency
public function currency() {
    return $this->hasMany(Currency::class);
}

Currency Model:

// relationship to location 
public function location() {
    return $this->belongsTo(Location::class);
}

It use hasMany because the model can have many another model. see : https://laravel.com/docs/9.x/eloquent-relationships#one-to-many

And it use belongsTo becasue the model can have many another model but inverse. see : https://laravel.com/docs/9.x/eloquent-relationships#one-to-many-inverse

In eloquent when you want to get some data, you can call it with whereHas in the Controller. see : Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean?

Amri
  • 77
  • 8