Reputation: 956
I am working with Laravel 5.4. I am using Eloquent ORM. I have created to table as Countries and States. Both are dislpay as below :
Countries Table :
States Table :
Now, I have wrote two method to set relationship between States and Countries table.
Country Model :
public function states()
{
return $this->hasMany('App\Models\Masters\State')->select('*');
}
State Model :
public function country()
{
return $this->belongsTo('App\Models\Masters\Country')->select('name as country_name');
}
Now, I am going to create edit functionality so I can not get country name.
I have written query as
$state = State::with('country')->find($id);
return Response($state);
Here, I got only state data and country data as null.
So what should I have to change to get state as well country data?
Upvotes: 0
Views: 895
Reputation: 111829
You should rather not use select
in your relationships. When you use only name of country Laravel won't be able to link this with your state, so it won't work.
You should define your relationships like this:
public function country()
{
return $this->belongsTo(\App\Models\Masters\Country::class);
}
public function states()
{
return $this->hasMany(\App\Models\Masters\State::class);
}
without selects
Upvotes: 3