Hi everyone,
Well, I bought a database of cities that came with 3 tables
countries:
country_code
country_name
states:
country_code
state_code
state_name
cities:
country_code
state_code
citiy_name
My models looks like this
// Country Model
class Country extends \Eloquent {
public $timestamps = false;
public function states()
{
return $this->hasMany('State', 'country_code', 'country_code');
}
public function cities()
{
return $this->hasMany('City', 'country_code', 'country_code');
}
}
// State Model
class State extends \Eloquent {
public $timestamps = false;
public function country()
{
return $this->belongsTo('Country', 'country_code', 'country_code');
}
public function cities()
{
return $this->hasMany('City', 'state_code', 'state_code');
}
}
// City Model
class City extends \Eloquent {
public $timestamps = false;
public function state()
{
return $this->belongsTo('State', 'state_code', 'state_code');
}
public function country()
{
return $this->belongsTo('Country', 'country_code', 'country_code');
}
}
Now when eager load the state from city
City::with('state')->get();
Gives me the wrong state because the state_code is not unique, so I need a way to set the relationship where
states.state_code = cities.state_code
AND
states.country_code = cities.country_code
I tried something like this but doesn't work
public function state()
{
return $this->belongsTo('State', 'state_code', 'state_code')
->where('country_code', $this->country_code);
}
Any help will be appreciated, thank you in advance.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community