Matthew Odedoyin
Matthew Odedoyin

Reputation: 84

many-to one relationship Eloquoent Orm

I have a challenge with Eloquent ORM for laravel am actually a newbie into this Eloquoent orm .i have a Model Country and a Model State. The state table has a foreign_key countryId. The issue is if i fetch all the states using eager loading with relationship as follows.

$countries = State::with('country')->get();

and my State model is as follows

class State extends Model
{
    protected $fillable = ['name', 'countryId'];
    protected $table = 'states';
    function Country(){
        return $this->belongsTo('Country','id');
    }
}

The result i get is as follows

[
{
"id": 1,
"name": "Lagos",
"countryId": "1",
"created_at": "2017-03-09 13:09:12.000",
"updated_at": "2017-03-09 13:09:12.000",
"country":{"id": 1, "name": "Nigeria", "created_at": "2017-03-09 10:55:46.000", "updated_at": "2017-03-09 10:55:46.000"…}
},
{
"id": 2,
"name": "Oyo",
"countryId": "1",
"created_at": "2017-03-09 13:29:12.000",
"updated_at": "2017-03-09 13:29:12.000",
"country": null
}
]

it can bbe seen from the json output that the second item country object is not loaded. i also tried to set a relationship on the Country model but no changes

class Country extends Model
{
    protected $fillable = ['name'];
    protected $table = 'countries';
    function State(){
        return $this->hasMany('State', 'countryId');
    }
}

thanks in anticipation of your response

Upvotes: 1

Views: 37

Answers (1)

EddyTheDove
EddyTheDove

Reputation: 13259

Try to fix your relationship first and try again. Define it this way in State model

public function country(){ //lower 'c' NOT capital 
    return $this->belongsTo(Country::class, 'countryId'); //Pass the class AND the foreign key. You passed the primary key
}

Then try again.

The reason the second one has no country is because you set 'id' in the relationship and there is no country with 'id' 2. So simply fix your relationship and you should be good to go.

Upvotes: 1

Related Questions