2014-02-19 165 views
0

假設我們有如下表:Laravel 4多對多關係

遊戲

GameQuestions

問題

答案

現在爲了獲得獲得相關問題單場比賽我得到了以下控制器片段:

if ($code) { 
      $gamedata = Game::with('questions') 
       ->where('secretcode', $code) 
       ->get(); 
     }else{ 
      $gamedata = Game::with('questions')->get(); 

     } 

我的繼承人遊戲模式:

class Game extends Eloquent { 


    /*table definition*/ 
    protected $table = 'games'; 


     public function questions(){ 
     return $this->belongsToMany('Question', 'gamequestions', 'game_id', 'question_id'); 
    } 

} 

並質疑型號:

類問題擴展雄辯{

/*table definition*/ 
protected $table = 'questions'; 

//questions relation 
public function answers(){ 
    return $this->hasMany('Answer', 'question_id', 'id'); 
} 

}

現在讓遊戲及其相關的問題似乎使用此代碼。 但是我也想包括答案。爲了適應另一個外鍵關係,需要修改這段代碼嗎?

回答

1

我相信你可以嵌套關係;

if ($code) { 
      $gamedata = Game::with('questions.answers') 
       ->where('secretcode', $code) 
       ->get(); 
     }else{ 
      $gamedata = Game::with('questions.answers')->get(); 

     } 

請參閱該文檔http://laravel.com/docs/eloquent#eager-loading - 搜索嵌套關係

$書=書::與( 'author.contacts') - >獲得();

在上面的例子中,作者關係將被急切加載,並且作者的聯繫關係也將被加載。

+0

非常好!謝謝。 – Tomkarho