Laravel Eloquent 关系没有结果
Laravel Eloquent Relationships has no results
我很难找到我在这里做错了什么。我有两张桌子:
Table 1: 状态(id, name)
Table 2: 城市 (id, name, state_id)
一个州有多个城市,一个城市属于一个州。
我这样声明模型:
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');
}
}
如果我尝试获取州并列出城市,在 Tinker 中,我只会得到一行作为答案。
$state_1 = App\Estado::find(1);
$state_1->cities();
给我:
Illuminate\Database\Eloquent\Relations\HasMany
更新:
我刚刚做了一个修改,它成功了!
但是我可以在 show 方法中从 CityController 得到一个结果:
City::with('state')->where('state_id',$id);
没有结果!
你需要做
$state_1->cities;
没有括号,获取实际的关系数据,而不是关系对象。
您可以阅读更多内容。
第一个问题电话:
$state_1->cities
对于更新后的问题,请执行以下操作:
City::with('state')->get(); /* the ->where('state_id',$id); shouldn't be
* required as you've already declared the relationship
*/
这可能会解决您的问题。如果 get() 未在您的 Eloquent 查询中定义,它将 return 什么都没有。
我很难找到我在这里做错了什么。我有两张桌子: Table 1: 状态(id, name) Table 2: 城市 (id, name, state_id)
一个州有多个城市,一个城市属于一个州。
我这样声明模型:
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');
}
}
如果我尝试获取州并列出城市,在 Tinker 中,我只会得到一行作为答案。
$state_1 = App\Estado::find(1);
$state_1->cities();
给我:
Illuminate\Database\Eloquent\Relations\HasMany
更新:
我刚刚做了一个修改,它成功了! 但是我可以在 show 方法中从 CityController 得到一个结果:
City::with('state')->where('state_id',$id);
没有结果!
你需要做
$state_1->cities;
没有括号,获取实际的关系数据,而不是关系对象。
您可以阅读更多内容
第一个问题电话:
$state_1->cities
对于更新后的问题,请执行以下操作:
City::with('state')->get(); /* the ->where('state_id',$id); shouldn't be
* required as you've already declared the relationship
*/
这可能会解决您的问题。如果 get() 未在您的 Eloquent 查询中定义,它将 return 什么都没有。