繁体   English   中英

Laravel 4多对多关系

[英]Laravel 4 many to many relationships

可以说我们必须有以下表格:

游戏

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');
}

}

现在,获取游戏及其相关问题似乎适用于此代码。 但是,我也想包括答案。 为了适应另一个外键关系,需要如何修改此代码?

我相信您可以嵌套关系;

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

        }

请参阅docs http://laravel.com/docs/eloquent#eager-loading-搜索嵌套关系

$ books = Book :: with('author.contacts')-> get();

在上面的示例中,将渴望加载作者关系,并且还将加载作者的联系人关系。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM