Laravel Eloquent nesting

2019-08-05 18:35发布

I'm trying to return nested JSON response, need to connect multiple tables, but for now, I'm just trying with 3, the levels can go deeper. My models are following:

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:

$sportovi = Sport::with('liga')->get(); 
return $sportovi;

everything is normal, children of "lige" are nested where they should be, as shown on the link here, but, if I try to add the Match, like this:

$mecevi = Sport::with('liga.mec')->get();

I get a "mec" node, which is an empty array, as shown here, instead going one level deeper, like in the previous example.

I've also tried making multiple with() conditions which throws an error Call to undefined method Illuminate\Database\Query\Builder::mec()

Update: Still the same, mec:[], empty array.

I'm using Laravel 4.2.

2条回答
Root(大扎)
2楼-- · 2019-08-05 19:24

Figured it out, my table relations were off, after giving all the conditions, like return $this->hasMany('Comment', 'foreign_key', 'local_key'); everything started working as it should. Thanks everybody.

查看更多
干净又极端
3楼-- · 2019-08-05 19:37

From my understanding, you want to get all the matches of leagues

The problem might be in the second parameter in hasMany function

public function mec(){
  return $this->hasMany('Match', 'league_id');
}

The second parameter need to be foreign_key

public function mec(){
  return $this->hasMany('Match', 'match_id', 'league_id');
}

source: http://laravel.com/docs/4.2/eloquent#one-to-many

查看更多
登录 后发表回答