foviho

Get the country through state

Posted 3 years ago by foviho

I created three models: Country, State and City, and the relationship is as follow:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Country extends Model
{
    public function states()
    {
        return $this->hasMany(State::class);
    }

    public function cities()
    {
        return $this->hasManyThrough(City::class, State::class);
    }
}
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class State extends Model
{
    public function cities()
    {
        return $this->hasMany(City::class);
    }

    public function country()
    {
        return $this->belongsTo(Country::class);
    }
}
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class City extends Model
{
    public function state()
    {
        return $this->belongsTo(State::class);
    }

    // country relation
}

As you can see I created a comment section // country relation is where I want to create a method to return the country that the city belongs to through state, but there's no relationship called belongsToThrough. How can I get all the country that the city belongs?

Please sign in or create an account to participate in this conversation.