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
via Hordedoyin Matthewg