Laravel Eloquent nesting
I'm trying to return a nested JSON response, multiple tables need to be connected, but while I'm just trying with 3, the levels can go deeper. My models are as follows:
Update # 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');
}
}
If I do this:
$sportovi = Sport::with('liga')->get();
return $sportovi;
everything is fine, the children of "lige" are nested where they should be, as shown in the link here , but if I try to add a Match, like this:
$mecevi = Sport::with('liga.mec')->get();
I get a "mec" node, which is an empty array as shown here , instead one level deeper as in the previous example.
I have also tried to make a few conditions () which cause the error Call undefined method Illuminate \ Database \ Query \ Builder :: mec ()
Update: still the same mec:[]
, empty array.
I am using Laravel 4.2.
source to share
From my point of view, you want to get everything matches
fromleagues
The problem could be in the second parameter in hasMany
function
public function mec(){
return $this->hasMany('Match', 'league_id');
}
The second parameter should be foreign_key
public function mec(){
return $this->hasMany('Match', 'match_id', 'league_id');
}
source to share