我试图返回嵌套的JSON响应,需要连接多个表,但就目前而言,我只是尝试使用3,这些级别可以更深入。我的模型如下:
更新#1:
class Sport extends Eloquent {
protected $table = 'sportovi';
protected $fillable = ['id', 'sport_eng'];
public $timestamps = false;
public function liga(){
return $this->hasMany('League', 'sport_id');
}
}
class League extends Eloquent {
protected $table = 'lige';
protected $fillable = ['league_id', 'liga', 'sport_id'];
public $timestamps = true;
public function mec(){
return $this->hasMany('Match', 'match_id');
}
}
class Match extends Eloquent {
protected $table = 'mecevi';
protected $fillable = ['match_id', 'home', 'away', 'kotime', 'day', 'kolo', 'sport_id', 'league_id', 'date', 'long_id'];
public $timestamps = false;
public function liga(){
return $this->belongsTo('Match', 'league_id');
}
}
如果我这样做:
$sportovi = Sport::with('liga')->get();
return $sportovi;
一切都很正常," lige"嵌套在它们应该的位置,如链接here所示,但是,如果我尝试添加匹配,就像这样:
$mecevi = Sport::with('liga.mec')->get();
我得到了一个" mec"节点,这是一个空数组,如here所示,而是更深一层,就像前面的例子一样。
我还尝试使用多个with()条件抛出错误 调用未定义的方法Illuminate \ Database \ Query \ Builder :: mec()
更新:仍然是mec:[]
,空数组。
我正在使用Laravel 4.2。
答案 0 :(得分:1)
根据我的理解,您希望得到matches
leagues
问题可能出在hasMany
函数
public function mec(){
return $this->hasMany('Match', 'league_id');
}
第二个参数需要为foreign_key
public function mec(){
return $this->hasMany('Match', 'match_id', 'league_id');
}
答案 1 :(得分:0)
想出来之后,在给出所有条件后,我的桌子关系都没了
return $this->hasMany('Comment', 'foreign_key', 'local_key');
一切都开始正常运作。谢谢大家。