簡體   English   中英

Laravel雄辯的嵌套

[英]Laravel Eloquent nesting

我正在嘗試返回嵌套的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;

一切正常,“李哥”的孩子們嵌套,他們應該是鏈接,如圖這里 ,但是,如果我嘗試添加了比賽,就像這樣:

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

我得到一個“MEC”節點,這是一個空數組,如圖所示這里 ,而不是去深入一層,像以前的例子那樣。

我也嘗試過使多個with()條件拋出錯誤, 調用未定義的方法Illuminate \\ Database \\ Query \\ Builder :: mec()

更新:仍然相同, mec:[]空數組。

我正在使用Laravel 4.2。

從我的理解,你想獲得所有matchesleagues

問題可能出在hasMany函數的第二個參數中

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

第二個參數需要為foreign_key

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

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

弄清楚了,給出所有條件后,我的表關系關閉了,例如return $this->hasMany('Comment', 'foreign_key', 'local_key'); 一切開始正常運行。 謝謝大家。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM