Laravel Eloquent 嵌套
Laravel Eloquent nesting
我正在尝试 return 嵌套 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" 的子级嵌套在它们应该在的位置,如 link here 所示,但是,如果我尝试添加匹配项,就像这样:
$mecevi = Sport::with('liga.mec')->get();
我得到一个 "mec" 节点,它是一个空数组,如图 here 所示,而不是更深一层,就像前面的示例一样。
我也试过使用多个 with() 条件来抛出错误
调用未定义的方法 Illuminate\Database\Query\Builder::mec()
更新:还是一样,mec:[]
,空数组。
我正在使用 Laravel 4.2。
据我了解,您想获得 leagues
的所有 matches
问题可能出在 hasMany
函数的第二个参数中
public function mec(){
return $this->hasMany('Match', 'league_id');
}
第二个参数需要foreign_key
public function mec(){
return $this->hasMany('Match', 'match_id', 'league_id');
}
想通了,我的 table 关系已经关闭,在给出所有条件之后,比如
return $this->hasMany('Comment', 'foreign_key', 'local_key');
一切都开始正常工作。谢谢大家
我正在尝试 return 嵌套 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" 的子级嵌套在它们应该在的位置,如 link here 所示,但是,如果我尝试添加匹配项,就像这样:
$mecevi = Sport::with('liga.mec')->get();
我得到一个 "mec" 节点,它是一个空数组,如图 here 所示,而不是更深一层,就像前面的示例一样。
我也试过使用多个 with() 条件来抛出错误 调用未定义的方法 Illuminate\Database\Query\Builder::mec()
更新:还是一样,mec:[]
,空数组。
我正在使用 Laravel 4.2。
据我了解,您想获得 leagues
matches
问题可能出在 hasMany
函数的第二个参数中
public function mec(){
return $this->hasMany('Match', 'league_id');
}
第二个参数需要foreign_key
public function mec(){
return $this->hasMany('Match', 'match_id', 'league_id');
}
想通了,我的 table 关系已经关闭,在给出所有条件之后,比如
return $this->hasMany('Comment', 'foreign_key', 'local_key');
一切都开始正常工作。谢谢大家