Reputation: 327
I am having trouble to find what I am doing wrong here. I have two tables: Table 1: State (id, name) Table 2: City (id, name, state_id)
One state has many cities, and one city belongs to a state.
I am declaring the models like this:
class City extends Model
{
protected $connection = 'pgsql';
protected $table = 'city';
public function state(){
return $this->belongsTo('App\State');
}
}
class State extends Model {
protected $connection = 'pgsql';
protected $table = 'state';
public function cities(){
return $this->hasMany('App\City','state_id','id');
}
}
If I try to get a state and list the cities, in the Tinker, I get just a line as an answer.
$state_1 = App\Estado::find(1);
$state_1->cities();
Gives me:
Illuminate\Database\Eloquent\Relations\HasMany
UPDATE:
I've just made a modification and it works! But I can get a result from the CityController, in the show method:
City::with('state')->where('state_id',$id);
has no results!
Upvotes: 0
Views: 1314
Reputation: 1439
For the first problem call:
$state_1->cities
For the updated question do this:
City::with('state')->get(); /* the ->where('state_id',$id); shouldn't be
* required as you've already declared the relationship
*/
This probably will resolve your problem. If get() is not defined in your Eloquent query it will return nothing.
Upvotes: 1
Reputation: 483
You need to do
$state_1->cities;
Without the parenteses, to get the actual relationship data, and not the relationship object.
You can read more here.
Upvotes: 0